public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
Property(p => p.Name).HasColumnName("ProductName");
}
}
我有实体框架的产品配置。我希望通过反思来使用它。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a =>
a.GetName().Name != "EntityFramework"))
{
var configTypes = assembly.GetTypes().Where(t =>
t.BaseType != null &&
t.BaseType.IsGenericType &&
t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var configType in configTypes)
{
if (configType.BaseType == null) continue;
??????Property(p => p.Name).HasColumnName("ProductName");
??????
}
}
}
答案 0 :(得分:0)
找到所有配置后,您需要创建实例并将其添加到modelBuilder.Configurations
:
foreach (var configType in configTypes)
{
if (configType.BaseType == null) continue;
dynamic configInstance = Activator.CreateInstance(configType);
modelBuilder.Configurations.Add(configInstance);
}
答案 1 :(得分:0)
您不必麻烦使用反射,EF已经为您完成了:)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.AddFromAssembly(typeof(ProductConfiguration).Assembly);
base.OnModelCreating(modelBuilder);
}