zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    【摘】IIS修复工具,怎么完全卸载IIS
    开启@yahoo.cn邮箱POP和SMTP的方法
    IT男士专用餐单(养生)
    使用wxWidgets编程——第一步
    搭建跨平台编程环境Code::Blocks+wxWidgets
    TANGO是一个开源的分布控制系统
    【摘】在Window下右键方式打开Dos命令窗口右键菜单支持DOS命令提示符号
    【原】美是永远的追求
    flascc移植问题流水账
    战棋游戏三国志英杰传分析
  • 原文地址:https://www.cnblogs.com/subendong/p/12401264.html
Copyright © 2011-2022 走看看