Suppose we have these two classes:
public class Parent
{
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 Parent Parent { get; set; }
}
Suppose I create one of each with the following methods:
//Create a parent with new children
public void CreateParent(MyDbContext context)
{
context.Parents.Add(new Parent
{
Children = new List<Child>()
{
new Child(),
new Child(),
new Child()
}
});
context.SaveChanges();
}
//Create a child with a new parent
public void CreateChild(MyDbContext context)
{
context.Children.Add(new Child
{
Parent = new Parent()
});
context.SaveChanges();
}
Will either of these methods create both Parent and Child objects with foreign keys appropriately assigned? My gut tells me that CreateParent would work, but CreateChild would not.
Yes, both of these methods will create the Parent and Child records as well with the ParentID foreign key set. If you run e.g. the first one, the result you will get will be the following:
And as another answer states you don't need the ParentID however Entity Framework will recognize it as the Foreign Key used for the Parent association and you don't have to use the virtual keyword neither at the Children nor at the Parent property to make your code work, however if you wan't Lazy Loading to work with these properties you will need them.