Nullability for strings vs. other data types in Entity Framework Code First columns

ef-code-first entity-framework


The columns in the produced database might have null values by default when a string is defined in a class using Code First.

    public string MyString { get; set; }

develops the column:

(nvarchar(max), null) MyString

I can use the "not null" command to change this to[Required] property or by using the Fluent API's.IsRequired() function.

Nulls are prohibited by other data kinds' defaults.

    public int MyInt { get; set; }
    public DateTime MyDateTime { get; set; }
    public float MyFloat { get; set; }
    public decimal MyDecimal { get; set; }
    public bool MyBool { get; set; }

the following columns:

MyInt (int, not null)

MyDateTime (datetime, not null)

MyFloat (real, not null)

MyDecimal (not null, decimal(18,2))

MyBool (bit, not null)

Using the Fluent API's.IsOptional() function, I may modify them to accept nulls. Exists a property that has the same effect?

Additionally, I may modify the data types in the class definition to permit nulls (int, DateTime, etc.), resulting in database columns that permit nulls.

Why are null values default-allowed for strings but not for other data types?

3/19/2012 1:32:16 PM

Accepted Answer

In a sense, you have provided an answer. A null reference cannot exist for any of the other data types you mentioned. Therefore, if the function cannot tolerate a null, it will ensure that the database enforces that as well.

Just to be sure you understand, as you are concentrating on a string rather than other value kinds. Here is the string article from the MDSN., you will see the following line if you search for null:

By contrast, a null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException

However, since an int must always have a default value, unless it is nullable, it will never raise a NullReferenceException.

3/19/2012 1:44:37 PM

Popular Answer

It's important to note that classes and strings are both nullable in EF Code First.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow