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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With