ove
ove

Reputation: 3202

Linq to EF .Clear() does not clear

EntityCollection.ToList().Clear()

Does not clear the entity collection. Any idea why?

Any solution?

How should i clear the EntityCollection?

Upvotes: 4

Views: 3127

Answers (2)

Torben Schramme
Torben Schramme

Reputation: 2140

Because ToList() creates a copy of the EntityCollection as a List<T> and then you just clear that list and not the EntityCollection itself.

Edit 1: Use the Clear() method from EntityCollection: http://msdn.microsoft.com/de-de/library/bb302707.aspx

Edit 2: Oh I see. So it's this class: http://msdn.microsoft.com/de-de/library/ff422654(v=vs.91).aspx ? Seems you have to enumerate all items and delete them one by one.

foreach( var item in EntityCollection.ToList() )
    EntityCollection.Remove(item);

Here you need ToList() to create a copy because most of the collection classes don't like it when you delete items from them during enumeration.

Upvotes: 4

ChristopheD
ChristopheD

Reputation: 116127

ToList() generates a new list (you are clearing that).

Upvotes: 0

Related Questions