gpt4 book ai didi

c# - 无法跟踪实体类型 'Item' 的实例,因为已跟踪具有相同键值 {'Id' } 的另一个实例

转载 作者:太空狗 更新时间:2023-10-29 21:37:33 28 4
gpt4 key购买 nike

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

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

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.

有趣的是,即使没有从数据库中检索到任何项目,异常也是相同的,就像这样

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

最佳答案

EF core 2.2 也有同样的问题。我从未在其他应用程序中体验过这一点。

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

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

关于c# - 无法跟踪实体类型 'Item' 的实例,因为已跟踪具有相同键值 {'Id' } 的另一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987635/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com