gpt4 book ai didi

c# - 使用 EF Core 删除范围

转载 作者:行者123 更新时间:2023-11-30 16:44:49 25 4
gpt4 key购买 nike

在我的单元测试中,使用 InMemoryDatabase 使用 RemoveRange 批量删除数据时出现错误。

代码如下:

public void DeletePatient(Paciente patient)
{
var schedules = dbContext.Schedules.AsNoTracking().Where(x => x.PatientId == patient.Id).ToList();
dbContext.Schedules.RemoveRange(schedules);

dbContext.Patients.Remove(patient);
}

这会引发此错误:

InvalidOperationException: The instance of entity type 'Schedule' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

但是,如果我执行 foreach 并重新加载每个实体,它会起作用:

foreach(var item in schedules)
{
var h = dbContext.Schedules.Find(item.Id);
dbContext.Remove(h);
}

同样的foreach,直接使用item报同样的错误:

foreach(var item in schedules)
{
dbContext.Remove(item);
}

最佳答案

尝试删除 AsNoTracking 子句。我还没有测试过,但我猜这会导致 EF 从数据库中重新读取实体,但找不到上下文中已有的实体。如果没有该子句,它应该在上下文中找到要删除的实际实体。

关于c# - 使用 EF Core 删除范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43139292/

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