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);
    }
}


免責聲明!

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



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