简体   繁体   中英

Assigning Entity Framework Code First Navigation Properties on Create

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.

Thank you!

Yes, both of these methods will create the Parent and Child records as well with the ParentID foreign key set. If you run eg 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.

Yes both functions work correctly, adding both Parent and Child records with the correct association between them.

Running CreateParent will yield one new Parent record and three Child records associated with it (through ParentID).

Running CreateChild will create one new Child and one new Parent record, associated correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM