c# - Use reflection to automate EF5 Code First DbModelBuilder -
i trying automate dbmodelbuilder object in onmodelcreating using reflection.
i have number of classes inherit base class: enumeration in database want able set id's of these tables in onmodelcreating call
modelbuilder.entity<someclass>() .property(sc => sc.someclassid) .hasdatabasegeneratedoption(databasegeneratedoption.none);
i automate using reflection because if forget when model applied database have delete , start again.
i know put attribute on class model don't want there.
here code. reason fails when try call generic method. have suggestions?
//get of models / tables want able specify proimary key for. var enumerationpropertyinfos = thisdbcontext .gettype() .getproperties(); .where(p => p.propertytype.isgenerictype && p.propertytype.getgenerictypedefinition() == typeof(dbset<>) && p.propertytype.getgenericarguments().first().basetype == typeof(myenumerationbase)); foreach (propertyinfo pi in enumerationpropertyinfos) { //modelbuilder.entity<someclass>() var config = modelbuilder.gettype() .getmethod("entity") .makegenericmethod(pi.propertytype) .invoke(modelbuilder, null); //prepare .property(...) var property = config.gettype().getmethods().where(m => m.name == "property").first(); var propertyexpression = typeof(expression<>) .makegenerictype(typeof(func<,>) .makegenerictype(pi.propertytype, typeof(int))); //prepare e => e.someclassid var paramex = expression.parameter(pi.propertytype.getgenericarguments().first(), "e"); var lambdaex = expression.lambda(expression.property(paramex, pi.propertytype.getgenericarguments().first().name + "id"), paramex); //execute .property(e => e.someclassid) primitivepropertyconfiguration propertyresult = (primitivepropertyconfiguration)property .makegenericmethod(typeof(expression)) .invoke(config, new[] { lambdaex }); propertyresult.hasdatabasegeneratedoption(databasegeneratedoption.none); }
you have 2 errors in code, first line:
//modelbuilder.entity<someclass>() var config = modelbuilder.gettype() .getmethod("entity") .makegenericmethod(pi.propertytype) .invoke(modelbuilder, null);
as equivalent to:
modelbuilder.entity<dbset<someclass>>();
change to:
var config = modelbuilder.gettype() .getmethod("entity") .makegenericmethod(pi.propertytype.getgenericarguments().first()) .invoke(modelbuilder, null);
the second error on line:
var propertyresult = (primitivepropertyconfiguration)property .makegenericmethod(typeof(expression)) .invoke(config, new[] { lambdaex });
you need pass type of someclassid
generic parameter property()
method passing typeof(expression)
instead. assuming someclassid of type int
change line to:
var propertyresult = (primitivepropertyconfiguration)property .makegenericmethod(typeof(int)) .invoke(config, new[] { lambdaex });
Comments
Post a Comment