Pascal Pascal - 1 year ago 173
C# Question

RemoveRange throws InvalidOperationException in Entity Framework Core

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 });
await context.SaveChangesAsync();

During runtime pupilIds are all different ids!

why do I get that error?

Answer Source

I think it will be

 var pupilsToDelete = context.Pupils.Where(a => pupilIds.Contains(a.Id)).Select(b => b);
 await context.SaveChangesAsync();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download