对于这个错误,要在SaveChanges前关闭验证实体有效性(ValidateOnSaveEnabled)这个开关
db.Configuration.ValidateOnSaveEnabled = false;//关闭验证
db.SaveChanges();
db.Configuration.ValidateOnSaveEnabled = true;//保存完之后再开启
或者,在创建EF上下文对象的时候,在线程中共享一个上下文对象
public DbContext GetDbContext()
{
DbContext dbContext = CallContext.GetData(typeof(DBContextFactory).Name) as DbContext;
if(dbContext == null)
{
dbContext = new IZhanShiEntities();
dbContext.Configuration.ValidataOnSaveEnabled = false;
//将新创建的EF上下文对象存入线程
CallContext.SetData(typeof(DBContextFactory).Name,dbContext);
}
return dbContext;
}