Search code examples
c#.netentity-framework.net-coreentity-framework-core

Why string property must be declared as nullable string in Entity Framework Core when corresponding database table column is nullable


Entity Framework Core version is 8.0. Here is my model.

    public class Item
    {
        [Key] public long ItemId { get; set; }

        public string KeyNumYear { get; set; }
        ...
    }

In database, KeyNumYear is nullable int column.

We have a row with null value in its KeyNumYear field. While using EfCore to query this row, I get below error.

System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'

But if I change it into public string? KeyNumYear { get; set; }, it will run successfully.

I am confused because I think string is already nullable in C#. Why do I have to mark it as string? in Entity Framework Core?


Solution

  • Ideally if the database column is a null-able int, the property in the entity should be:

    public int? KeyNumYear { get; set; }
    

    The reason string doesn't work is that EF will detect the type conversion and interpret the need for a string vs. a string? and need to apply a conversion, specifically a ToString(). #null.ToString() is invalid, where if declared as a null-able string EF will know to check for #null first before applying the ToString().

    string is a reference type, not specifically a null-able type. Prior to .Net Core 6 reference types were interpreted as being null-able by default. With .Net 6 they introduced explicit null-able reference types.