具體詳細錯誤信息: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。