c# - How can I map a base entity field to different columns for each subclass -
i have base entity class, want able inherit have write 1 getbyid method lots of different entity-specific repositories. however, "id" column in of database tables has called "code" legacy reasons.
i tried (simplified version):
public class entitybase{ int id; } public class identity : entitybase{ } public class codeentity : entitybase{ } and in dbcontext:
modelbuilder.entity<identity>(entity => { entity.haskey(e=>e.id).hasname("pk_identity"); entity.property(e=>e.id).hascolumnname("id"); } modelbuilder.entity<codeentity>(entity => { entity.haskey(e=>e.id).hasname("pk_codeentity"); entity.property(e=>e.id).hascolumnname("code"); //this seems breaks } this builds fine, when try run it, invalidoperationexception: cannot call property property 'id' on entity type 'codeentity' because configured navigation property. property can used configure scalar properties.
is i'm trying impossible? seems unlikely me, correct way it?
edit:
what trying turns out more complex "simplified" code posted here. wanted make have string or int id, , use same getbyid method. created class had implicit conversions both string , int, thought ok entity framework.
it's not.
the runtime error caused trying tell ef property entityid type should key, you're not allowed do.
i couldn't find documentation microsoft requirements key values in entity framework, found question said scalars , byte[] allowed keys: type safe keys entity framework model
i not above code compile or give exception getting enough after trying fix it. though describe how write scenario trying achieve.
if want use entitybase.id pk property in ef, need make public property. in code, private field (since no get/set methods). entitybase class should this
public class entitybase { public int id { get; set; } } with above changes , onmodelcreating code map entity types posted in question, model building works correctly creating tables desired table structure , names.
following small method implementing generic getbyid on dbset. can made part of generic repository or extension method.
public static t getbyid<t>(dbset<t> dbset, int id) t : entitybase { return dbset.firstordefault(e => e.id == id); } // example var entity = getbyid(db.set<identity>(), 2);
Comments
Post a Comment