How do I delete a child entity from a parent collection with Entity Framework 4?

你离开我真会死。 提交于 2019-12-03 07:26:30

It depends on whether you have a cascade in the DB. If you do (and, given your question, you probably should), then this should be automatic. You can read about this here.

What I've come across to solve this problem is the follwoing override on the DbContext:

public override int SaveChanges()
{
    Set<Child>()
    .Local
    .Where(r => !Parent.Local.SelectMany(s => s.Children).Contains(r))
    .ToList()
    .ForEach(r => Set<Child>().Remove(r));

    return base.SaveChanges();
}

Take a look here: http://blog.oneunicorn.com/2012/06/02/deleting-orphans-with-entity-framework/

In EF4, if the child objects and the parent object are all attached to the ObjectContext, then EF will keep the Foreign Key references and Object References in-sync in both the Parent and the affected Children.

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