简体   繁体   中英

EntityTypeConfiguration property method by reflection

public class ProductConfiguration : EntityTypeConfiguration<Product>
{
    public ProductConfiguration()
    {
        Property(p => p.Name).HasColumnName("ProductName");
    }
}

I have a product configuration of entity framework. I want to use this by reflection.

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");
                         ??????
                    }
                }
}

After finding all configurations you need to create instance of them and add them to modelBuilder.Configurations :

foreach (var configType in configTypes)
{
    if (configType.BaseType == null) continue;

     dynamic configInstance = Activator.CreateInstance(configType);
     modelBuilder.Configurations.Add(configInstance);
}

You dont have to go through the trouble of using reflection, EF has already done it for you :)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.AddFromAssembly(typeof(ProductConfiguration).Assembly);
    base.OnModelCreating(modelBuilder);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM