无法跟踪实体类型“ Item”的实例,因为已经跟踪了具有相同键值的“ {'Id”}的另一个实例 [英] The instance of entity type 'Item' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

查看:853
本文介绍了无法跟踪实体类型“ Item”的实例,因为已经跟踪了具有相同键值的“ {'Id”}的另一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经问过这样的问题,但是解决方案并没有帮助我。

I am aware that such question has already been asked, but solution did not help me.

[Fact]
public async Task UpdateAsync()
{
    string newTitle = "newTitle1";
    int newBrandId = 3;
    var item = await storeContext.Items.AsNoTracking().FirstOrDefaultAsync();
    item.BrandId = newBrandId;
    item.Title = newTitle;
    storeContext.Entry(item).State = EntityState.Detached;
    await service.UpdateAsync(item); // exception inside
    var updatedItem = await storeContext.Items.AsNoTracking().FirstOrDefaultAsync();
    Assert.Equal(newTitle, updatedItem.Title);
    Assert.Equal(newBrandId, updatedItem.BrandId);
}

public async Task UpdateAsync(T entity)
{
    _dbContext.Entry(entity).State = EntityState.Modified; // exception when trying to change the state
    await _dbContext.SaveChangesAsync();
}




消息:System.InvalidOperationException:无法跟踪实体类型项目,因为已经跟踪了另一个具有相同的{'Id'}键值的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看有冲突的键值。

Message: System.InvalidOperationException : The instance of entity type 'Item' 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.



,就像这样

interesting that exception is the same even if no item retreived from db, like so

//var item = await storeContext.Items.AsNoTracking().FirstOrDefaultAsync();
  var item = new Item()
  {
      Id = 1,
      BrandId = newBrandId,
      CategoryId = 1,
      MeasurementUnitId = 1,
      StoreId = 1,
      Title = newTitle
  };


推荐答案

EF核心2.2遇到相同的问题。我从未在其他应用程序上遇到过这种情况。

Had the same problem with EF core 2.2. I never experianced this with other applications.

最终以某种方式重写了我所有的更新功能:

Ended up rewriting all my update functions somehow like this:

public bool Update(Entity entity)
{
    try
    {   
       var entry = _context.Entries.First(e=>e.Id == entity.Id);
       _context.Entry(entry).CurrentValues.SetValues(entity);
       _context.SaveChanges();
       return true;
    }
    catch (Exception e)
    {
         // handle correct exception
         // log error
         return false;
    }
}

这篇关于无法跟踪实体类型“ Item”的实例,因为已经跟踪了具有相同键值的“ {'Id”}的另一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆