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?