mardi 2 avril 2019

Automate Configuring Mappings Using Reflection

i need to add Automatic Mapping Configuration in DBModelBuilder in C# .

i create this Mapping :

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

and use Create this extention Method for find all Mapping and Configur That in 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) });
                }
            }
        }
    }

and i use that in model builder :

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

but when i use the Enable-Migrations it show me this Error :

Sequence contains no matching element

whats the problem ? how can i solve this problem ?





Aucun commentaire:

Enregistrer un commentaire