EFCore 重写DbContext.SaveChanges方法,避免多个实例跟踪发生错误
重写DbContext的保存方法,避免多个DbContext实例跟踪相同的实体发生错误
重写DbContext.SaveChanges方法
C#全选
/// <summary>
/// 重写DbContext的保存方法,避免多个DbContext实例跟踪相同的实体发生错误
/// </summary>
/// <returns></returns>
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
finally
{
this.Detach();
}
}
C#全选
/// <summary>
/// 取消跟踪
/// </summary>
public void Detach()
{
this.ChangeTracker.Entries().ToList().ForEach(aEntry =>
{
if (aEntry.State != EntityState.Detached)
aEntry.State = EntityState.Detached;
});
}
使用方法
C#全选
internal int DeleteLog(List<string> isids)
{
var list = _Database.sys_UpgraderLog
.Where(w => isids.Contains(w.isid)).ToList();
_Database.RemoveRange(list);
return _Database.SaveChanges();
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网