实体框架6 - 如何添加子实体?

时间:2015-02-10 21:44:03

标签: entity-framework

在EF6中添加子实体的正确方法是什么?为什么Parent.Children.Add(child)抛出NullReferenceException(Children集合为null)?如果Parent.Children集合至少有一个项目,则.Add(子)可以正常工作。我究竟做错了什么?这是我在MVC项目中的代码示例:

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

1 个答案:

答案 0 :(得分:2)

您需要在Children的构造函数中初始化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>();
   }
}