Tag Archives: EF An error occurred while updating the entries. See the inner exception for details.

[Solved] EF An error occurred while updating the entries. See the inner exception for details.

EF add data when the insert failed id can not be null, but we have the value assigned.

System.Data.SqlClient.SqlException: cannot insert value NULL into column ‘ID’, table ‘dbo.Sys_MenuBasis’; column is not allowed to have NULL value.

This is caused by ef treating data with id attribute as self-adding id

Solution:

public class ERPContext : DbContext
{
public ERPContext():base(“ERPContext”)
{
}
public IDbSet<Sys_MenuBasis> Sys_MenuBasis { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Sys_MenuBasis>().Property(p => p.ID).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
}
}

Or add to the entity primary key attribute

public class Sys_MenuBasis
{

[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public long ID { get; set; }

}

Done!