asp.net mvc - Entity Framework Mapping. Multiple Foreign keys -
i have 2 tables
people relation ------------- ----------------- id (int) id (int) name (string) parentpeopleid (int) childpeopleid (int) i need people relation table union all. relation table has 2 foreign keys. , there 1 problem mapping them. mapping 1 many. people has many relation, relation has 1 people.
i mapped them this:
hasrequired(r=> r.people).withmany(p=>p.relation).hasforeignkey(r=>r.childpeopleid); so, how can map second foreign key?
per each fk column in relations table should have navigation property in relation entity (this not mandatory, mandatory have @ least 1 navigation property between entities involve in relationship). in case have 2 relationships between people , relations, , navigation property represents 1 end in relationship. model way:
public class relation { public int id {get;set;} public int parentpeopleid {get;set;} public int childpeopleid {get;set;} public virtual people parentpeople {get;set;} public virtual people childpeople {get;set;} } public class people { public int id {get;set;} public string name {get;set;} public virtual icollection<relation> parentrelations {get;set;} public virtual icollection<relation> childrelations {get;set;} } and fluent api configurations this:
hasrequired(r=> r.parentpeople ).withmany(p=>p.parentrelations ).hasforeignkey(r=>r.parentpeopleid); hasrequired(r=> r.childpeople).withmany(p=>p.childrelations ).hasforeignkey(r=>r.childpeopleid ); now if don't want work 1 of collection navigation properties in people entity, can create unidirectional relationship. example if don't want parenrelations navigation property, can configure relationship follow:
hasrequired(r=> r.parentpeople).withmany().hasforeignkey(r=>r.parentpeopleid); update
let me start first suggestion. thing table relation not playing role have columns. if person con have parent change model following:
public class people { public int id {get;set;} public string name {get;set;} public int parentid {get;set;} public virtual people parent {get;set;} public virtual icollection<people> children {get;set;} } and relationship configuration be:
hasoptional(r=> r.parent).withmany(p=>p.children).hasforeignkey(r=>r.parentid); now going current model, ef sees childpeopleid property simple scalar column, doesn't know it's fk column, that's way suggested above map 2 relationship instead one.
another thing, below line
var peoplelist = mydbcontext.people.include(p=>p.relations.select(r=>r.people)).tolist(); you telling ef want load relation entities related people, want load people related each relation, @ same time same people relation came from, so, don't need last select, if data related, people navigation property going loaded when execute query,so, query should way:
var peoplelist = mydbcontext.people.include(p=>p.relations).tolist();
Comments
Post a Comment