Alexander
Alexander

Reputation: 1061

Reference to objects lost afer adding a new item

I have a model that looks like this:

public class Parent
{
    public string Name { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public string Name { get; set; }

    public Parent Parent { get; set; }

    public Child ParentChild { get; set; }
    public List<Child> Children { get; set; }
}

That means that I have a parent that can have children. The children can also have children. Each child has a reference to the parent it belongs to (even if it is a child of a child).

I have the following in my database:

Parent

I now want to add Child_1_2.

var child = new Child(){ Name = "Child 1.2" };
child.ParentChild = child_1;
child.Parent = parent;

context.Children.Add(child);
context.SaveChanges();

My problem is now that this will change Child_1_1 and Child_1_1_1. The reference to their parent will be lost after this Code. They will be null in the database. This has something to do with Entity Framework not loading all the references (especially not references that are nested).

Is there a way to do this and tell the Entity Framework to add the Parent but not change the parent or any of its children?

Upvotes: 0

Views: 65

Answers (1)

flindeberg
flindeberg

Reputation: 5017

My guess is that you are not showing the exact model here. Your model would mean two different tables.

A quick fix would be to add parent.Children.Add(child).

Although I would severely recommend you to redo your model into something similar (although still doesn't make sense in a larger contex):

public class Person
{
   public string Name { get; set; }
   public List<Child> Children { get; set; }
}

public class Parent : Person
{
   // Probably this class would contain something useful
}

public class Child : Person
{
    public Person ParentPerson { get; set; }
}

Upvotes: 1

Related Questions