inheritance - Base class as foreign key in Entity Framework Code First -
lets have classes:
public class basemodel { [key] public int id { get; set; } } public class person : basemodel { public string firstname { get; set; } public string lastname { get; set; } public datetime dateofbirth { get; set; } public string email { get; set; } } public class employee : person { public string position { get; set; } public decimal wage { get; set; } public paymenttype paymenttype { get; set; } public virtual company company { get; set; } } currently have this:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { base.onmodelcreating(modelbuilder); modelbuilder.entity<employee>().hasrequired(e => e.paymenttype); modelbuilder.entity<employee>().map(t => { t.mapinheritedproperties(); t.totable("employees"); }); modelbuilder.entity<company>().hasmany(c => c.employees).withrequired(e => e.company).map(t => t.mapkey("company_id")); } i 2 tables person , employee, don't mapinheritedproperties() adding person properties employee table.
how make base class(person) foreign key?
in order use base class foreing key / navigational property without primary key problems. need using table per type or table per hierarchy.
in case using modelbuilder should it.
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { base.onmodelcreating(modelbuilder); modelbuilder.entity<employee>().hasrequired(e => e.paymenttype); modelbuilder.entity<person >().totable("persons"); modelbuilder.entity<employee>().totable("employees"); modelbuilder.entity<company>().hasmany(c => c.employees).withrequired(e => e.company).map(t => t.mapkey("company_id")); } with 2 table created. on names persons fields person , 1 "employees" fields employee. both table share same primary key
you can detailed explaination on mortenza manavi's blog
Comments
Post a Comment