entity framework - Two properties of same type mapping to a single table which has a column to distinguish the target property -
entity framework - Two properties of same type mapping to a single table which has a column to distinguish the target property -
i have 2 tables:
parents id childs parent_id child_number
and 2 corresponding entity-types want type parent have 2 navigation properties linking first , sec child:
class parent property child1 : kid property child2 : kid
i searching along lines of
modelbuilder.entity<parent>() .map(f => f.child1, m => m.requires("child_number").hasvalue(0)) modelbuilder.entity<parent>() .map(f => f.child2, m => m.requires("child_number").hasvalue(1))
is possible without having 2 destinct, derived types child1 : child
, child2 : child
?
while i'm sure it's possible have dynamic childn
type/property, go different approach. that's i'm going suggest.
i think in situation create more sense have parent
reference collection of children, rather explicitly having properties child1
,child2
,...,childn
.
i advocate not solves problem (or @ to the lowest degree fulfills needs) allow potential future extension. if did this, you'd end handling selection of 1st,2nd,...,nth kid separate piece of logic.
instead end 2 pocos parent , child
public class parent() { public parent() { children = new hashset<child>(); } [required] public int id {get;set}| //collection of kid objects navigation property public virtual icollection<child> children{get;set;} } public class child() { [required] public int parentid {get;set} [required] public int childnumber{get;set} //collection of kid objects navigation property public virtual parent parent {get; set;} }
fluent api mapping. fluent api code include [required] info property
s isrequired()
, easier me stick in model definition, , would've crowded more of import mapping info of fluent api.
mbuilder.entity<parent>().haskey(p=>p.id); mbuilder.entity<parent>().hasmany(p=>p.children) .withrequired(c=>c.parent) .hasforeignkey(c=>c.parentid); mbuilder.entity<child> .haskey(c=> new {c.parentid, c.childnumber});
one possible approach retrieving nth child
getnthchild(parent, n) { homecoming parent.children.where(c => c.childnumber ==n); }
or define own children class implements indexer nth child; how decide go getting nth kid you.
entity-framework ef-code-first entity-framework-6
Comments
Post a Comment