Nullable property to entity field, Entity Framework through Code First

chrisramon picture chrisramon · May 22, 2012 · Viewed 145.5k times · Source

Using the data annotation Required like so:

[Required]
public int somefield {get; set;}

Will set somefield to Not Null in database, How can I set somefield to allow NULLs?, I tried setting it through SQL Server Management Studio but Entity Framework set it back to Not Null.

Answer

danludwig picture danludwig · May 23, 2012

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }