2
在EF6中添加子實體的正確方法是什麼?爲什麼Parent.Children.Add(child)拋出NullReferenceException(Children集合爲null)?如果Parent.Children集合至少包含一個項目,則.Add(子項)將起作用。我究竟做錯了什麼?下面是從MVC項目我的代碼示例:實體框架6 - 如何添加子實體?
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();
}
}