Entity Framework via Code First, nullable property to entity field

asp.net-mvc-3 code-first entity-framework nullable

Question

Making use of the data annotationRequired like this:

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

somefield will be set toNot Null How can I configure database somefield to accept NULLs? , While using SQL Server Management Studio, I attempted to change it, but Entity Framework changed it back to Not Null.

1
69
7/27/2015 1:10:46 PM

Accepted Answer

Simply leave the [Required] property off of thestring somefield property. This will cause it to develop aNULL column in the database.

Integer types must be designated as nullable ints in the model in order for the database to support NULLs for them:

// 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; }
107
5/5/2015 7:20:22 PM

Popular Answer

The alternative is to instruct EF to permit a null value for the column:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

The object that inherits from should include this code.DbContext .



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