简体   繁体   中英

How to remove a subset of items from an Entity Framework Collection

I have an entity framework EntityCollection .

I need to delete all items that match a given where clause from the database. This is my existing code:

// Perform the deletes
foreach (var deleteReq in order.Requirements.Where(x=>!orderContract.Requirements.Any(y=>y.RequirementId==x.RequirementId)))
{
    order.Requirements.Remove(deleteReq);
}

Basically I am trying to remove anything from the order.Requirements collection that is not in the orderContract.Requirements collection (matching on an Id).

As you may guess, this code throws and exception because I am modifying the collection I am iterating.

Normally I would just use RemoveAll() but the EntityCollection does not support that method.

So... How can I delete all the records I need to?

I created a seperate list and it seems to have worked:

// Perform the deletes
var reqsToDelete = order.Requirements.Where(x=>!orderContract.Requirements.Any(y=>y.RequirementId==x.RequirementId)).ToList();
foreach (var deleteReq in reqsToDelete)
{
    order.Requirements.Remove(deleteReq);
}

That way, when I remove the item from the order.Requirements list, it is not affecting the list that I am iterating.

collect all the Requirement entities you want to delete into a list.

Then remove each one of those from the Requirements entity collection rather than from order.Requirements.

Prior to EF6, there is a RemoveRange method for better performance and cleaner API

var deleteQuery = order
    .Requirements
    .Where(x=> !orderContract.Requirements.Any(y=>y.RequirementId == x.RequirementId));

order.Requirements.RemoveRange(deleteQuery);

Now, the EF wont load each item before remove, as it is a case in the accepted answer.

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