使用反射自动配置映射

时间:2019-04-02 11:49:12

标签: c# entity-framework reflection entity-framework-6

我需要在C#的DBModelBuilder中添加自动映射配置。

我创建此映射:

 public class ProductMapping : EntityTypeConfiguration<Product>
{
    public ProductMapping(DbModelBuilder builder)
    {
        HasRequired(x => x.ProductUnit).WithMany(x => x.Products).HasForeignKey(x => x.UnitId);
    }
}

 public class TransactionMapping : EntityTypeConfiguration<Transaction>
{
    public TransactionMapping()
    {
        HasRequired(x => x.Product).WithMany(x => x.Transactions).HasForeignKey(x => x.ProductId);
        HasRequired(x => x.Contractor).WithMany(x => x.Transactions).HasForeignKey(x => x.ContractorId);
    }
}

并使用创建此extention Method来查找DbModelBuilder中的所有映射和配置:

        public static void RegisterEntityTypeConfiguration(this DbModelBuilder modelBuilder, params Assembly[] assemblies)
    {
        MethodInfo applyGenericMethod = typeof(DbModelBuilder).GetMethods().First(m => m.Name == nameof(DbModelBuilder.Configurations.Add));

        IEnumerable<Type> types = assemblies.SelectMany(a => a.GetExportedTypes())
            .Where(c => c.IsClass && !c.IsAbstract && c.IsPublic);

        foreach (Type type in types)
        {
            foreach (Type iface in type.GetInterfaces())
            {
                if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>))
                {
                    MethodInfo applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                    applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
                }
            }
        }
    }

我在模型构建器中使用它:

            var asseblyconfiguration = typeof(EntityTypeConfiguration<>).Assembly;
        modelBuilder.RegisterEntityTypeConfiguration(asseblyconfiguration);

但是当我使用Enable-Migrations时,会显示此错误:

  

序列中没有匹配的元素

出什么问题了?我该如何解决这个问题?

0 个答案:

没有答案