c# - Entity Framework: New parent is saved, new children are not -


i have following classes:

public class parentobject {     [databasegenerated(databasegeneratedoption.identity), key]     public int id { get; set; }      public string name { get; set; }      [foreignkey("parentid")]     public list<childobject> childobjects { get; set; } }  public class childobject {     [databasegenerated(databasegeneratedoption.identity), key]     public int id { get; set; }      public int parentid { get; set; }      public string name { get; set; } } 

i have method adding new parent new child:

private void add(string parentname, string childname) {     using (mydbcontext context = new mydbcontext ()) {         parentobject newparent = new parentobject { name = parentname };         childobject newchild = new childobject { name = childname };         newparent.childobjects = new list< childobject> { newchild };             context.parentobjects.add(newparent);         context.savechanges();     } } 

the parent saved database, child not. understanding having foreign key constraint should tie (the foreign key exists on db tables). can't figure out i'm missing make child save database.

the collection property needs virtual

public virtual icollection<childobject> childobjects { get; set; } 

it's navigational property, not collections. without virtual keyword, entityframework's dynamic proxies unable override property , foreign key tracking want do.


Comments