c# - Entity framework self referencing key not writing to database -


i have entity framework code first object self referencing key. child records don't have parent id in self referencing key when data written database.

public class contract {     public contract()     {         contracts = new list<contract>();     }       public int id { get; set; }     public list<contract> contracts { get; set; }  } 

the object has many more properties above i've simplified sake of example. not many many relationship. each contract has 1 parent, apart master contracts have no parents.

when add sub contract list of contracts , call savechanges on dbcontext, contract , sub contract written database fields correct. apart entity framework generated field contract_id null.

i've got similar self referencing keys working correctly other classes, in fact contract has these classes properties. these other classes work expected, self referencing keys indicating parent object populated correctly.

i've created simple test class same above test prepended class name , works correctly. i've created simple test contract class , not work correctly.

what i'd able debug entity framework savechanges method i'm not sure that's possible.

does have idea in terms of i've done wrong or how debug this?

you have modify entity that:

public class contract {   public contract()   {     this.contracts  = new list<contract>();   }   public int id { get; set; }    public int? contractparentid   {     get; set;    }    public contract contractparent { get; set; }   public list<contract> contracts { get; set; } } 

and use that:

using (var dbcontext = new mydatabasecontext(productionconnectionstring)) {   // need fixup   var contract1 = dbcontext.contracts.create<contract>();   var contract2 = dbcontext.contracts.create<contract>();    dbcontext.contracts.add(contract1);   dbcontext.contracts.add(contract2);    contract1.contracts.add(contract2);    dbcontext.savechanges(); } 

you have modify dbcontext, because not possible define type of relation in code first need fluent api:

protected override void onmodelcreating(dbmodelbuilder modelbuilder) {   modelbuilder.entity<contract>().hasoptional(c => c.contractparent).withmany(c => c.contracts).hasforeignkey(c => c.contractparentid);   base.onmodelcreating(modelbuilder); } 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -