Reputation: 1434
What's the correct way to add child entities en EF6? Why does Parent.Children.Add(child) throw NullReferenceException (Children collection is null)? If the Parent.Children collection has at least one item then the .Add(child) works. What am I doing wrong? Here is my code example from a MVC project:
public class Parent
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public int ID { get; set; }
public string Name { get; set; }
public int ParentID { get; set; }
public Parent Parent { get; set; }
}
public class AppContext : DbContext
{
public AppContext() : base("AppContext") {}
public DbSet<Parent> Parent { get; set; }
public DbSet<Child> Children { get; set; }
}
public class AppContextInitializer : System.Data.Entity.DropCreateDatabaseAlways<AppContext>
{
protected override void Seed(AppContext context)
{
Parent parent = new Parent { Name = "John" };
Child child = new Child() { Name = "Mary" };
parent.Children.Add(child); // Doesn't work: System.NullReferenceException, Children==null
Parent parent2 = new Parent { Name = "Robert" };
Child child2 = new Child { Name = "Sarah", Parent=parent2 };
context.Children.Add(child2); // Works.... even inserts the parent entity thru the child entity!!
context.SaveChanges();
}
}
Upvotes: 2
Views: 1796
Reputation: 39326
You need to initialize the Children
navigation property in a constructor of Parent
:
public class Parent
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
public Parent()
{
Children=new List<Child>();
}
}
Upvotes: 3