entity framework - N to M relationship code first does not create the foreign key on the M-table -
a schoolclasscode can have many pupils.
a pupil can belong many schoolclasscodes.
this n m relation.
i thought n m relation work in code first default.
but explicitly create n m relation here:
modelbuilder.entity<schoolclasscode>(). hasmany(c => c.pupils). withmany(p => p.schoolclasscodes). map( m => { m.mapleftkey("schoolclasscodeid"); m.maprightkey("pupilid"); m.totable("schoolclasscodepupil"); }); public class schoolclasscode { public schoolclasscode() { pupils = new hashset<pupil>(); tests = new hashset<test>(); } public int id { get; set; } public string schoolclasscodename { get; set; } public string subjectname { get; set; } public int color { get; set; } public string classidentifier { get; set; } public iset<pupil> pupils { get; set; } public iset<test> tests { get; set; } public schoolyear schoolyear { get; set; } public int schoolyearid { get; set; } } public class pupil { public pupil() { pupilstests = new hashset<pupiltest>(); schoolclasscodes = new hashset<schoolclasscode>(); } public int id { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string postal { get; set; } public string city { get; set; } public string street { get; set; } public iset<pupiltest> pupilstests { get; set; } public iset<schoolclasscode> schoolclasscodes { get; set; } }
on pupil table no foreign key created @ all, why this?
for many many relationship, there no foreign key on either side. foreign keys on join table, have mapped table schoolclasscodepupil
:
modelbuilder.entity<schoolclasscode>(). hasmany(c => c.pupils). withmany(p => p.schoolclasscodes). map(m => { m.mapleftkey("schoolclasscodeid"); m.maprightkey("pupilid"); m.totable("schoolclasscodepupil"); });
entity framework uses junction table determine belongs in somepupil.schoolclasscodes
set.
Comments
Post a Comment