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

c# entity-framework

Question

I have a framework for entities.EntityCollection .

I have to remove from the database any entries that meet a certain where clause. Here is my current code:

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

In essence, I'm attempting to exclude anything from the sequence. collection of requirements not covered by the order contract. requirement gathering (matching on an Id).

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

Usually, I'd simply useRemoveAll() even so,EntityCollection does not back that technique.

So, how can I remove every record I require?

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

Accepted Answer

I separated the lists, and it seemed 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);
}

In this approach, the list I am iterating is unaffected when I delete the item from the order.Requirements list.

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

Popular Answer

Make a list of all the Requirement entities you wish to remove.

Then, rather than removing them from order, delete each of them from the Requirements entity collection. 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