All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S3363.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

You should only set a property of a temporal type (like DateTime or DateTimeOffset) as the primary key of a table if the values are guaranteed to be unique.

Why is this an issue?

Using temporal types as the primary key of a table is risky. When these types are used as primary keys, it usually means that each new key is created with the use of .Now or .UtcNow properties from DateTime and DateTimeOffset classes. In those cases, duplicate keys exceptions may occur in many ways:

  • when entries are added consecutively by a machine with low-enough system clock resolution;
  • when two different threads are inserting entries in close enough sequence for both to have the same time;
  • when changes such as daylight saving time (DST) transitions occur, where values can be repeated the following hour (only for DateTime type);

The rule raises an issue if:

How to fix it

Either use a GUID or the auto generated ID as a primary key.

Code examples

Noncompliant code example

internal class Account
{
    public DateTime Id { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
}

Compliant solution

internal class Account
{
    public Guid Id { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
}

or

Noncompliant code example

internal class Person
{
    [Key]
    public DateTime PersonIdentifier { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
}

Compliant solution

internal class Person
{
    [Key]
    public Guid PersonIdentifier { get; set; }

    public string Name { get; set; }
    public string Surname { get; set; }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy