简体   繁体   中英

Delete a list of items in Entity Framework

I am trying to clear all items from an Entity Framework collection, in this case, remove all food from a plate. Any ideas how I can resolve the following - The code below generates the error:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Plate selPlate = (Plate)Session["selPlate"];

foreach (FoodForPlate f in selPlate.FoodForPlates)
{
    context.Entry(f).State = System.Data.Entity.EntityState.Deleted;
}

context.SaveChanges();

bindstats();

UpdatePanel1.Update();

Entity Framework keeps track of your loaded items so it can detect changes and you have some of those objects loaded already. Try:

dbContext.Entry(entity).State = EntityState.Detached;

You can also try disabling object tracking but that depends on your application requirements.

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