添加、删除或更新具有子实体的对象

Add,delete or update a Object with children entities

我有一个父模型,其中包含子模型的集合,现在这个子模型有一个 childofchild 的集合,它是一个复杂的模型。 我想添加、更新或删除 Child 或 ChildOfChild 实体,如果我是我的 Parent 模型,因为 EF 5 有很多更改或新方法我已经在网上搜索但没有发现可以解决我这个问题。

现在在 EF 7、lineQ 或扩展库中是否有一个好的方法来以简单或干净的方式更新它。 我的错误解决方案是进行多次检查的 foreach...

public class Parent
{
    public Parent()
    {
        this.Children = new List<Child>();
    }

    public int Id { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }

public virtual ICollection<ChildOfChild> Children { get; set; }


    public string Data { get; set; }
}

public class ChildOfChild
{
    public int Id { get; set; }


    public string Data { get; set; }
}

你的模型是多余的,只用一个模型就够了:

型号:

public class Entity
{
    public int ID { get; set; }
    public string Data { get; set; }

    public virtual Entity Parent { get; set; }
    public int? ParentID { get; set; }

    public virtual ICollection<Entity> Children { get; set; }
}

代码示例:

var dc = new DataContext();
var parent = dc.Entitys.Add(new Entity { Data = "Parent" });
dc.SaveChanges();

dc.Entitys.Add(new Entity { Data = "Child1", ParentID = parent.ID });
dc.Entitys.Add(new Entity { Data = "Child1", ParentID = parent.ID });
var child = dc.Entitys.Add(new Entity { Data = "Child1", ParentID = parent.ID });
dc.SaveChanges();

dc.Entitys.Add(new Entity { Data = "Child2", ParentID = child.ID });
dc.SaveChanges();