What is the best way to delete a subset of objects from an Entity Framework Collection?

c# entity-framework

Question

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?

1
5
10/18/2011 8:21:50 PM

Accepted Answer

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.

12
10/18/2011 8:35:30 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow