在数据库更新时,
1 首先查找数据库是否包含该项
2 然后更新该项目获添加,
在先查找的时候已经跟踪数据
第二步插入会报错The instance of entity type ‘XXX’ cannot be tracked
这里使用的是Microsoft.EntityFrameworkCore的数据库DbContext
using (YieldInfoDatabase context = new YieldInfoDatabase() { Path = SysStatus.ProductPath })
{
try
{
context.Database.EnsureCreated();
foreach (var data in datalist)
{
var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime).ToList();//这里先查找了数据已经将对应数据放入缓存跟踪,所以就报错
context.Entry(data).State = (records?.Count ?? 0) > 0 ?
EntityState.Modified : EntityState.Added;
}
context.SaveChanges();
return EmRes.Succeed;
}
catch (Microsoft.Data.Sqlite.SqliteException ex)
{
Logger.Error($"写入数据失败{ex.ToString()}");
return EmRes.DbWriteErr;
}
catch (Exception ex)
{
Logger.Error($"写入数据失败{ex.ToString()}");
return EmRes.DbWriteErr;
}
}
以上代码会报错:
System.InvalidOperationException:“The instance of entity type ‘XXX’ cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.”
var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime).ToList();
这里先查找了数据已经将对应数据放入缓存跟踪,所以就报错
应该修改为
var records = context.DataPerHour.Where(x => x.CurTime == data.CurTime ).AsNoTracking().ToList();