Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 Delete Object from entity collection

I have a "Request" Entity with an 1..* relationship to the "RequestProperty" Entity. So there's a collection of RequestProperty objects in "Request". When I update a "Request" I want to delete all items in the RequestProperty EntityCollection and add the new items from the incoming domain object. When I iterate over the Request.Properties collection and call a remove or a DeleteObject on the item, the enumeration fails because the collection has been modified.

As of now I'm doing this:

while (true)
{
    if (newRequest.Properties.Count > 0)
        context.RequestPropertySet.DeleteObject(newRequest.Properties.First());
    else
        break;
}

Since this is not really "cool" I thought there must be another way to empty a collection of a relationship. Thank you for your thoughts.

like image 436
hoetz Avatar asked Feb 07 '11 14:02

hoetz


2 Answers

The answer depends on the way you modeled your entities. If you are using common independent relation or foreign key relation you will have to use your current approach - I'm using it as well in my project.

If you defined identifying relation you will be able to call just Clear on collection as @Craig described. Identifying relation is special relation where primary key of dependent entity contains foreign key of parent entity.

Example EF model

The example shows Order entity and OrderItem entity with foreign key identifying relation between them. Primary key of OrderItem consists of unique Id and OrderId which is FK of Order table. With this configuration you don't need to iterate through OrderItems and delete each item separately. Simply removing OrderItem from collection will be executed as delete in database and clearing collection will delete all related OrderItems in database.

like image 101
Ladislav Mrnka Avatar answered Oct 15 '22 14:10

Ladislav Mrnka


Use the Clear() method:

newRequest.Properties.Clear();
like image 43
Craig Stuntz Avatar answered Oct 15 '22 12:10

Craig Stuntz