The instance of entity type 'xxx' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.


具體詳細錯誤信息:The instance of entity type 'xxx' 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 item in list)
                {
                    var func = this.GetCodeCheckFunction(item);
                    var gauge = UnitWork.FindSingle(func);

                    if (gauge == null)
                    {
                        //新增
                        UnitWork.Add(item);
                    }
                    else
                    {
                        //修改
                        gauge.GaugeType = item.GaugeType;
                        gauge.ModifiedBy = _auth.GetCurrentUser().User.Id;
                        gauge.ModifiedTime = DateTime.Now;
                        UnitWork.Update(gauge);
                    }
                    UnitWork.Save();
                }

介紹下業務場景:導入時excel中存在重復數據。更新數據用的UnitWork。

上面的報錯信息很明顯了,它告訴我們一條數據已經被trace了,不能重復trace,只要我們把這條被trace的數據取消就行了。

下面是修改后的代碼:

                foreach (var item in list)
                {
                    var func = this.GetCodeCheckFunction(item);
                    var gauge = _dbContext.MesInfoGauges.FirstOrDefault(func);

                    if (gauge == null)
                    {
                        //新增
                        _dbContext.MesInfoGauges.Add(item);
                        _dbContext.SaveChanges();
                        _dbContext.Entry(item).State = EntityState.Detached;
                    }
                    else
                    {
                        //修改
                        gauge.GaugeType = item.GaugeType;
                        gauge.ModifiedBy = user.Id;
                        gauge.ModifiedTime = DateTime.Now;
                        _dbContext.MesInfoGauges.Update(gauge);
                        _dbContext.SaveChanges();
                        _dbContext.Entry(gauge).State = EntityState.Detached;
                    }
                }

保存后,修改當前數據的Entry狀態為Detached。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM