mardi 30 juin 2015

RuntimeBinderException when dynamic call HasMany

When I want to use reflection to setup the DbContext, I get a RuntimeBinderException. My code is looks like:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var types = MyAsembly.GetExportedTypes();

        var typesOfBaseEntity = types.ToList().FindAll(t => t.IsSubclassOf(typeof(MyEntity)));
        foreach (var t in typesOfBaseEntity)
        {
            MethodInfo method = typeof(MyComponent).GetMethod("SetPrimaryKey");
            MethodInfo generic = method.MakeGenericMethod(t);

            generic.Invoke(this, new object[] { modelBuilder });
        }
     }

    public void SetPrimaryKey<T>(DbModelBuilder modelBuilder) where T : MyEntity
    {
        modelBuilder.Entity<T>().HasKey(t => t.Uid);

        foreach (var prop in typeof(T).GetProperties())
        {
            if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                // Creating Lambda, for example: t => t.ListOfSomethig

                Type type = prop.PropertyType.GetGenericArguments()[0];     
                type = typeof(List<>).MakeGenericType(type);
                type = typeof(Func<,>).MakeGenericType(typeof(T), type);

                var arg = Expression.Parameter(typeof(T), "t");
                Expression expr = Expression.Property(arg, prop);

                dynamic lambda = Expression.Lambda(type, expr, arg);

                modelBuilder.Entity<T>().HasMany(lambda).WithOptional();//Here it throw exception!!
            }
        }
    }   

If I use the common API, such as "modelBuilder.Entity().HasMany(a => a.SubComps)" it works fine. But why the reflection one cannot work? Anyone can help?





Aucun commentaire:

Enregistrer un commentaire