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

ef-code-first entity-framework

Question

When defining a string in a class using Code First, the default for the columns in the generated database allows nulls.

    public string MyString { get; set; }

creates this column:

MyString (nvarchar(max), null)

I can change this to "not null" by using the [Required] attribute or by using the .IsRequired() method in the Fluent API.

The default for other data types does not allow nulls.

    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; }

creates these columns:

MyInt (int, not null)

MyDateTime (datetime, not null)

MyFloat (real, not null)

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

MyBool (bit, not null)

I can change these to allow nulls by using the .IsOptional() method in the Fluent API. Is there an attribute that will do the same thing?

I can also change the data types in the class definition to allow nulls (int?, DateTime?, etc.) which results in columns that allow nulls in the database.

What is the rationale for allowing nulls by default for strings but not for other data types?

1
8
3/19/2012 1:32:16 PM

Accepted Answer

You kind of answered this yourself. You cannot have a null reference to any of the other data types that you listed. So, if the code cannot handle a null, then it is going to make sure the database enforces that, also.

Just to make this perfectly clear, as you are focusing specifically on a string versus other value types. Here is the MDSN article on strings, if you search for null, you will see this line:

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, unless an int is nullable, it will never throw a NullReferenceException since it must always have a default value.

5
3/19/2012 1:44:37 PM

Popular Answer

Useful to add that not only strings are nullable in EF Code First, but also classes.



Related Questions





Related

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