C# 有没有更好的方法在EF中实现OnModelCreating方法?
我们有一个实现DbContext的products类。OnModelCreating方法的代码如下:C# 有没有更好的方法在EF中实现OnModelCreating方法?,c#,entity-framework,C#,Entity Framework,我们有一个实现DbContext的products类。OnModelCreating方法的代码如下: modelBuilder.Configurations.Add(new CustomProductMap()); modelBuilder.Configurations.Add(new CustomProductDetailMap()); modelBuilder.Configurations.Add(new CustProdCatMappingMap()); modelBuilder.
modelBuilder.Configurations.Add(new CustomProductMap());
modelBuilder.Configurations.Add(new CustomProductDetailMap());
modelBuilder.Configurations.Add(new CustProdCatMappingMap());
modelBuilder.Configurations.Add(new CustProductSKUMap());
...
这里逐个添加实体
我确信有更好的方法来实现这一点,要么使用反射,要么使用IoC容器
有人能给我举个例子让我自己实现吗?您可以使用以下查询来获取从EntityTypeConfiguration或ComplexTypeConfiguration继承的类型实例:
var maps = from a in AppDomain.CurrentDomain.GetAssemblies()
where a.GetName().Name != "EntityFramework" // skip EF assembly
from t in a.GetTypes()
where t.BaseType != null && t.BaseType.IsGenericType
let baseDef = t.BaseType.GetGenericTypeDefinition()
where baseDef == typeof(EntityTypeConfiguration<>) ||
baseDef == typeof(ComplexTypeConfiguration<>)
select Activator.CreateInstance(t);
请记住,我使用dynamic
关键字,因为activator返回类型为object
的实例。因此,我们需要根据实际的映射类型调用适当的重载Add
方法
foreach (var map in maps)
modelBuilder.Configurations.Add((dynamic)map);