EF The instance of entity type 'XX' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
使用EF的时候,获得了一个Alist,先对Alist的子项做了修改,然后把Alist丢到新方法里面,新方法用Blist做了循环接受然后做update(),此时系统报错
System.InvalidOperationException: The instance of entity type 'PaperDocument' cannot be tracked because another instance with the same key value for {'Id'} 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.
原代码
foreach (var t in papers)
{
t.Status = status;
t.DelayReason = $"{UserAccount}操作撤销";
t.ClosingDeadline = DateTime.Now.AddDays(2).Date;
}
UpdatePaperDocumentStatus(papers);
public int UpdatePaperDocumentStatus(List<PaperDocument> paperDocuments)
{
List<PaperDocument> papers = new List<PaperDocument>();
List<PaperDistribution> paperDistributions = new List<PaperDistribution>();
foreach (PaperDocument item in paperDocuments)
{
PaperDocument dbPaperDoc = this.dataContext.PaperDocuments.AsNoTracking()
.FirstOrDefault(t => t.Id == item.Id);
if (dbPaperDoc == null)
continue;
dbPaperDoc.Status = item.Status;//改变状态
papers.Add(dbPaperDoc);
}
this.dataContext.PaperDistributions.UpdateRange(paperDistributions);
this.dataContext.PaperDocuments.UpdateRange(papers);
return this.dataContext.SaveChanges();
}
修改后代码
foreach (var t in papers)
{
t.Status = status;
t.DelayReason = $"{UserAccount}操作撤销";
t.ClosingDeadline = DateTime.Now.AddDays(2).Date;
this._dataContext.SaveChanges();
this._dataContext.Entry(t).State = EntityState.Detached;
}
其余代码不变
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?