简体   繁体   中英

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 (ie 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?

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

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․

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM