Reputation: 82341
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?
Upvotes: 7
Views: 9572
Reputation: 8008
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.
Upvotes: 3
Reputation: 82341
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.
Upvotes: 12
Reputation: 1802
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.
Upvotes: 6