RemoveRange throws InvalidOperationException in Entity Framework Core

c# entity-framework-core

Question

I get the error:

The instance of entity type 'Pupil' 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.

I would understand this error if I would have retrieved before this instance which is then loaded in the context cache, but I haven`t!!!

    var pupilsToDelete = pupilIds.Select(id => new Pupil { Id = id });
    context.RemoveRange(pupilsToDelete.ToList());
    await context.SaveChangesAsync();

During runtime pupilIds are all different ids!

why do I get that error?

1
1
10/18/2016 7:39:31 PM

Accepted Answer

To remove records needs to be track able from the context. So instead of create new collection of Pupil just reference them from context

 var pupilsToDelete = context.Pupils.Where(a => pupilIds.Contains(a.Id)).Select(b => b);
 context.Pupils.RemoveRange(pupilsToDelete);
 await context.SaveChangesAsync();
2
10/18/2016 8:24:44 PM

Popular Answer

To be able to remove records, you need to make sure your ObjectContext is tracking them. Best way to remove items as is answered by @Mostafiz, but you can also attach your entities to context.

var pupilsToDelete = pupilIds.Select(id => new Pupil { Id = id });
foreach(var p in pupilsToDelete )
   context.Attach(p);
context.RemoveRange(pupilsToDelete.ToList());
await context.SaveChangesAsync();

Which is not good approach․



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