EntityCollection Clear() and Remove() methods

前端 未结 5 1959
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 04:53

What is the right way to delete all of the collection items of an EF entity? In the code below, DocumentItems is the collection of related document items for a document. Thi

5条回答
  •  心在旅途
    2021-01-04 05:42

    Clear just removes the reference but doesn't delete the entity.

    In your situation

    existing.DocumentItems.Clear();  
    

    All DocumentItems in the EntitySet will get cleared but you will have to Remove/Delete the actual DocumentItem or the commit with fail, just the same as it would if you tried to delete it in the database.

    You need to loop through detach any references, and then delete the entity you wish to remove (unless its nullable and in your situation, it is not)


    Alternatively, I have seen implementations that use clear, and an AssociationChangedHandler to automatically delete the old object. Basically, if the change is a "delete/remove" it calls DeleteObject() on the orphaned object.

提交回复
热议问题