我遇到了这个问题Adding to or updating an entity in a foreach loop takes too long time before calling SaveChanges()?
我通过在BackgroundWorker
中运行代码解决了这个问题。它可以工作,因为保存只需要2秒而不是15秒。但每当调用DbSet.Count()
时,抛出此异常(我猜任何其他调用DbSet
的方法都会抛出相同的异常):
System.InvalidOperationException:'实体对象不能 由IEntityChangeTracker的多个实例引用。'
在DoWork
方法中对此行触发的异常:
oContext.TbHistoryLogDetails.Add(details);
我只是对DoWork
处理程序被调用的方式和原因感到困惑,它是否应该仅在调用RunWorkerAsync()
时运行?!
修改
正如我所说,DoWork
方法现在包含Save方法中的代码:
private void Worker_SaveLog(object sender, DoWorkEventArgs e)
{
foreach (var item in Sublist.OrderBy(x => x.Serial))
{
var ser = SerializeObject(item);
var record = oContext.TbHistoryLog_Lists.FirstOrDefault(x => x.ListObjectJson == ser);
if (record == null) //add new list item
{
TbCommonHistoryLog_Lists listObject = new TbCommonHistoryLog_Lists()
{
ListObjectJson = SerializeObject(item)
};
var details = new TbCommonHistoryLogDetails { TbHistoryLog = log, TbHistoryLog_Lists = listObject };
oContext.TbHistoryLogDetails.Add(details);
}
else //attach an existing list item
{
var o = oContext.TbHistoryLog_Lists.Find(record.Id);
oContext.TbHistoryLog_Lists.Attach(o);
var details = new TbCommonHistoryLogDetails { TbHistoryLog = log, TbHistoryLog_Lists = o };
oContext.TbHistoryLogDetails.Add(details);
}
}
oContext.BulkSaveChanges();
}