Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Vaccano Avatar asked Oct 18 '11 20:10

Vaccano


2 Answers

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.

like image 197
Vaccano Avatar answered Oct 21 '22 09:10

Vaccano


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.

like image 24
Birey Avatar answered Oct 21 '22 07:10

Birey