c# - How do I build this EF relationship? -
c# - How do I build this EF relationship? -
i can in database want understand how code-first.
i have class:
public class component { public guid id { get; set; } public guid name { get; set; } public virtual component master { get; set; } public virtual icollection<component> components { get; set; } }
a component can have many kid components. component can kid component in many other components.
i want create table relates component's id's together. best way represent this?
when have self referencing entity can have single parent:
public class component { public guid id { get; set; } public guid name { get; set; } public virtual component master { get; set; } public virtual icollection<component> components { get; set; } // reference parent guid (if any) public guid? masterid { get; set; } }
to configure entity relationship in onmodelcreating:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<component>() .hasmany(c => c.components) .withoptional(c => c.master) .hasforeignkey(fk => fk.masterid); }
another alternative set xref / bring together table instead of having column on components table, in case have many many relationship instead of single component master, have collection of components master. can enforce ever single parent using unique key, still have model collection ef's perspective.
here illustration of using xref table:
public class component { public guid id { get; set; } public guid name { get; set; } public virtual icollection<component> masters { get; set; } public virtual icollection<component> components { get; set; } } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<component>() .hasmany(c => c.components) .withmany(c => c.masters) .map(xref => xref.mapleftkey("parentid").maprightkey("childid").totable("componentxref")); }
c# entity-framework asp.net-mvc-4 ef-code-first
Comments
Post a Comment