How to remove a subset of items from an Entity Framework collection

I have an entity infrastructure EntityCollection.

I need to remove all elements matching the where where query 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);
}

I am basically trying to remove something from the order.Requirements of a collection that is not in the orderContract.Requirements of the collection (matching on Id).

As you can guess, this code generates and excludes because I am modifying the collection that I am executing.

Normally I would just use RemoveAll(), but EntityCollectiondoes not support this method.

So ... How can I delete all the records that I need?

+5
source share
3 answers

, , :

// 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);
}

, order.Requirements, , .

+11

, , .

, . .

+6

Prior to EF6, there is a method RemoveRangefor better performance and a cleaner API

var deleteQuery = order
    .Requirements
    .Where(x=> !orderContract.Requirements.Any(y=>y.RequirementId == x.RequirementId));

order.Requirements.RemoveRange(deleteQuery);

Now EF will not load every element before deletion, as this is the case in the accepted answer.

+1
source

All Articles