entity framework - EF Code First Parent-Child insertions with identity columns -


i have following model.

class parent {     int parentid (identity column) { get; set; }     string parentname { get; set; }     virtual icollection<child> children { get; set; } }  class child {     int childid (identity column) { get; set; }     string childname { get; set; }     int parentid { ; set; } //foreign key parent(parentid) } 

how insert few rows parent , child in single transaction? want identity generated on parent(say insert row in parent) , insert child rows value? how can achieved using code first?

you shouldn't worry value id of parent in order insert child rows. should enough:

var parent = new parent {     // fill other properties      children = new list<child>() }  parent.children.add(new child { /*fill values */);  dbcontext.parents.add(parent); // whatever context named dbcontext.savechanges(); 

for record, id's assigned after calling savechanges(), if really need id before inserting child entity can call savechanges() twice.

again, shouldn't necessary though.

by way, recommend making foreign key property child parent navigation property, child class like:

class child {     public int childid { get; set; } // identity column     public string childname { get; set; }     public virtual parent parent { ; set; } //foreign key parent } 

that way can access child's parent directly without having retrieve explicitly database (it lazy loaded).


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -