c# - EntityFramework code first manually setting PKs which are FKs to other tables -
i using entityframework codefirst existing database. encountering problems keys. have created 4 test tables , models simulate situation:
party - the main container class.
public class party { // id generated @ database public int id { get; set; } public virtual icollection<partyrole> partyroles { get; set; } }
roletype - type separate data according role.
public class roletype { // static library table need generate id public short id { get; set; } public string value { get; set; } }
partyrole - roles of parties
public class partyrole { // partyid , roletypeid composite pk public int partyid { get; set; } // fk party public short roletypeid { get; set; } // fk roletype public virtual party party { get; set; } public virtual roletype roletype { get; set; } public virtual icollection<insurer> insurers { get; set; } }
insurer
public class insurer { public int id { get; set; } // partyid , roletypeid composite fk partyrole public int partyid { get; set; } public short roletypeid { get; set; } // other properties public virtual partyrole partyrole { get; set; } }
i have not included mapping details simplicity. mapping details correct , written using fluent api. when try manually set pks of partyrole , insert values not reflected @ insurer:
using (mytestcontext testcontext = new mytestcontext()) { insurer insurer = new insurer(); partyrole partyrole = new partyrole() { partyid = 1, // party id exist roletypeid = 1, // roletype id exist insurers = new list<insurer>() { insurer } }; testcontext.set<partyrole>.add(partyrole); testcontext.savechanges(); }
when execute above code generates following sql statements:
insert "party_roles" ("id", "role_type_id") values (1 /* :p0 */, 1 /* :p1 */); insert "insurers"( "party_id", "role_type_id") values ( 0 /* :p0 */, 0 /* :p1 */);
my question why ef sends (0, 0) insert insurers should (1, 1)?
if partyid , roletypeid not fks in partyrole model send (1, 1).
ef couldn't guess this. can manually set keys insurer:
insurer insurer = new insurer() { partyid = 1, roletypeid = 1 }; ... testcontext.savechanges();
Comments
Post a Comment