其他分享
首页 > 其他分享> > EF The instance of entity type 'XX' cannot be tracked because another instance with the s

EF The instance of entity type 'XX' cannot be tracked because another instance with the s

作者:互联网

使用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;
        }

其余代码不变

标签:dataContext,tracked,List,instance,key,papers
来源: https://www.cnblogs.com/shenzhoulong/p/16532233.html