Domi
Domi

Reputation: 1399

Add,delete or update a Object with children entities

I have a parent model which contains a collection of child, ok now this child has an collection of childofchild, it is a complex model. I want to add, update or delete Child or ChildOfChild entities if my of my Parent model, since EF 5 there are many changes or new methodes I already searched in the net and found nothing that could solve me this.

Is there a good methode now in EF 7,lineQ or with a extended libary to update this in a easy or clean way. My bad solution would be a foreach with multiple checkings...

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; }
}

Upvotes: 0

Views: 90

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13508

Your models are redundant, it enough to use only one model:

Model:

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; }
}

Code sample:

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();

Upvotes: 1

Related Questions