c# - Is there a better way to implement OnModelCreating method in EF? -


we have products class implements dbcontext. onmodelcreating method has code so:

 modelbuilder.configurations.add(new customproductmap());  modelbuilder.configurations.add(new customproductdetailmap());  modelbuilder.configurations.add(new custprodcatmappingmap());  modelbuilder.configurations.add(new custproductskumap());  ... 

here entities added 1 one.

i sure there's better way either using reflection or using ioc container.

can show me example can implement myself?

you can use following query instances of types inherited entitytypeconfiguration or complextypeconfiguration:

var maps = in appdomain.currentdomain.getassemblies()            a.getname().name != "entityframework" // skip ef assembly            t in a.gettypes()                                    t.basetype != null && t.basetype.isgenerictype            let basedef = t.basetype.getgenerictypedefinition()            basedef == typeof(entitytypeconfiguration<>) ||                  basedef == typeof(complextypeconfiguration<>)            select activator.createinstance(t); 

all need after adding maps modelbuilder configurations:

foreach (var map in maps)     modelbuilder.configurations.add((dynamic)map); 

keep in mind, use dynamic keyword because activator returns instances type object. need call appropriate overload of add method based on actual map type.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -