【发布时间】:2018-12-01 21:55:46
【问题描述】:
我知道已经有人问过这样的问题,但解决方案对我没有帮助。
[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:无法跟踪实体类型“Item”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。
有趣的是,即使没有从 db 中检索到任何项目,异常也是相同的,就像这样
//var item = await storeContext.Items.AsNoTracking().FirstOrDefaultAsync();
var item = new Item()
{
Id = 1,
BrandId = newBrandId,
CategoryId = 1,
MeasurementUnitId = 1,
StoreId = 1,
Title = newTitle
};
【问题讨论】:
-
尝试删除此
storeContext.Entry(item).State = EntityState.Detached;,然后像您在问题末尾所做的那样手动创建项目 -
确保单元测试中使用的
DbContextstoreContext与服务中使用的实例service相同。 -
确保没有其他线程可以持有这个对象
-
@tomassino 一样,没有任何改变。即使只运行一个测试,错误也会保留,所以我怀疑线程。
-
@CodeNotFound 是一样的,只是包装在仓库里。