EFCore删除记录报错:The instance of entity type 'xxx' cannot be tracked because another instance with the same key value for {'isid'} is already being tracked
System.InvalidOperationException:“The instance of entity type 'sys_UpgraderPackageTable' cannot be tracked because another instance with the same key value for {'isid'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.”
目录
解决方案
1、重写DbContext的保存方法,避免多个DbContext实例跟踪相同的实体发生错误
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;
});
}
2、使用DbContext操作数据,如修改、删除实体后,必须调用 SaveChanges()方法。
参考代码:
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();
}
C# 全选
public bool InsertPackage(sys_UpgraderPackageTable data)
{
data.isid = Globals.GetId();
_Database.Add(data);
return _Database.SaveChanges() == 1;
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网