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

EF新增数据时报插入失败id不能为null, 但是我们有赋值。

System.Data.SqlClient.SqlException: 不能将值 NULL 插入列 'ID',表 'dbo.Sys_MenuBasis ';列不允许有 Null 值。INSERT 失败。

这里是因为ef把数据带有id属性都当成自增id导致的

解决的方法

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);
}
}

或者在实体主键属性上加


public class Sys_MenuBasis
{

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

}

希望能帮到有需要的你

猜你喜欢

转载自www.cnblogs.com/xiang-wei/p/9200562.html