Removing range using EF Core

c# entity-framework entity-framework-core

Question

I´m getting an error when using RemoveRange to bulk delete data, in my unit tests, using InMemoryDatabase.

Here is the code:

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

This throws this error:

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.

But, if I perform a foreach and reload each entity, it works:

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

The same foreach, using the item directly gives same error:

foreach(var item in schedules)
{
    dbContext.Remove(item);
}
1
3
3/31/2017 11:14:20 AM

Accepted Answer

Try removing the AsNoTracking clause. I haven't tested it but my guess is this is causing EF to re-read the entities from the database and not finding the ones already in the context. Without the clause it should find the actual entities in the context to be removed.

2
3/31/2017 11:19:36 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow