SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
766 stars 226 forks source link

Fix S1144 FP: When having read only Id properties on entity types in EF Core #9416

Open mary-georgiou-sonarsource opened 2 months ago

mary-georgiou-sonarsource commented 2 months ago

Description

In EF Core, once properties are being set via the constructor, it can make sense to make some of them read-only. EF Core supports this, but there are some things to look out for:

An easy way to avoid these things is to use private setters. Although the setters seem unused, in reality, EF Core is using the field in an extralinguistic manner.

See MSDN docs for more information.

Repro steps

public class Blog
{
    public Blog(int id, string name,)
    {
        Name = name;
    }

    public int Id { get; private set; }            // FP
    public string Name { get; private set; }
}

Expected behavior

It should not raise for properties on classes representing entities in EF core that have unused private setters.

gsaltd-core commented 1 month ago

I noticed a test has been created for this, but it hasn't yet been fixed. Is this likely to be fixed soon as we are having to supress this error.

guimabdo commented 1 week ago

I think not only EF Entity Ids. When desiging an Entity in EF you may want to have any other property that is filled from a database column that is set from outside the application and should not be changed in the code.

And not only EF, you may want to desserialize a JSON into a class object that should not allow setting properties in the code. The serializer needs the private setters.