zoukankan      html  css  js  c++  java
  • The instance of entity type 'XXX' cannot be tracked because another instance with the same key value for {'XX'} is already being tracked.

    在做单元测试的时候碰到以下报错:

    The instance of entity type 'XXX' cannot be tracked because another instance with the same key value for {'XX'} 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.
    

    具体报错代码如下:

    项目平时运行是没问题的,但在单元测试时会报错,可能跟在测试时一个方法里多次调用有关。
    我的做法如下:使用try catch,在异常里操作
    1、修改状态 Entry (entity).State = EntityState.Detached;
    2、再次调用本身

    具体代码如下:

    public void Detach<T> (T entity) where T : class 
    {
        Entry (entity).State = EntityState.Detached;
    }
    
    public void EditRange<T> (ICollection<T> entities) where T : class 
    {
        Set<T> ().UpdateRange (entities.ToArray ());
    }
    
    public virtual void EditRange(ICollection<T> entities, bool again = true)
    {
        bool TryAgain = again;
        try
        {
            _dbContext.EditRange(entities);
        }
        catch (Exception ex)
        {
            if (TryAgain)
            {
                foreach (var item in entities)
                {
                    Detach(item);
                }
                EditRange(entities, false);
                return;
            }
            throw new Exception(ex.Message);
        }
    }
    
  • 相关阅读:
    java入门 (七) 面向对象(三)
    java入门 (七) 面向对象(二)
    java入门 (七) 面向对象(一)
    ajax异步请求,$.each遍历拼接数据
    java入门 (六) 数组(二)
    java入门 (六) 数组(一)
    java入门 (五) 方法
    微信小程序
    776C Molly's Chemicals --- 前缀和
    CF 458C Elections --- 三分|线段树
  • 原文地址:https://www.cnblogs.com/hwxing/p/14179404.html
Copyright © 2011-2022 走看看