How to Clear() all elements from Entity Framework ICollection?

守給你的承諾、 提交于 2019-12-05 07:08:35

There is a difference between your two code samples.

Your first code sample dbContext.RemoveRange(postsToRemove) removes the Post records. Therefor, any relationship involving these records are also removed.

In your second code sample myBlog.Posts.Clear() you are removing the relationship between myBlog and its corresponding Post records. The 'real' underlying action is to set the value of BlogId of the Post records to null. Unfortunately this is not possible, since BlogId is set to not-nullable. So, in short, the relationship is removed, and no records are actually deleted.

Clear works on the relationship and not on deleting the entity.

There is a working (I think more readable) half way solution between the two solutions you wrote.

dbContext.Posts.RemoveRange(myBlog.Posts);
// Now (also before SaveChanges) the myBlog.Posts is empty
dbContext.SaveChanges();

EDIT
RemoveRange also removes Posts from the Blog.Posts collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!