The blog has moved to the new site F10Debug.com

Sunday, June 26, 2016

Cannot insert the value NULL into column in ASP.NET MVC Entity Framework

Cannot insert the value NULL into column in ASP.NET MVC Entity Framework

One of my friend was trying simple MVC application [CRUD application] CRUD means 
C - Create, R - Read, U - Update & D- delete 

and he was getting error like "Cannot insert the value NULL into column in ASP.NET MVC Entity Framework" from almost more than half hour as below,

entity framework null value issue for id key

Here he was trying to save id & name into department table where id was not primary key of table.
Although he was specifying id value explicitly he was getting above error, because entity framework by default considers id as primary key and does not supply values to sql server.

Solution:

[Table("Department")]
    public class Department
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int id { get; set; }

        public string Name { get; set; }

    }

Here you just need to add one line above id property, to say entity framework that do not consider as database generated value.

If we want to set this option globally for every entities (for all tables), then we can do this by two ways as below,

- By setting identity specification set to false globally

  How to set identity specification set to false globally

- By creating custom conventions & add that custom conventions to DBContext class

  How to set DatabaseGeneratedOption Globally for all entities

- Using Fluent API

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder modBuilder) {
        modBuilder.Entity<MyEntity>()
                    .Property(e => e.Id)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

No comments:

Post a Comment