简体   繁体   中英

Entity Framework Model Builder Configuration using Reflection

I want to call the below code using reflection:

modelBuilder.Entity<CardPayment>().Map(m =>
            {
                m.MapInheritedProperties();
                m.ToTable("CardPayments");
            });

I am trying the following:

var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
entityMethod.MakeGenericMethod(type)
          .Invoke(modelBuilder, new object[] { });

How do I call the " Map " method with the parameters supplying the "Map" method. How can I invoke the " MapInheritedProperties " and " ToTable " methods within the "Map" method.

Thanks

You need to capture the return object from entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { }); , then you can dynamically invoke Map :

var mapLambda = 
      /* you'll need to fix the typing here */(m) => 
      { 
           m.MapInheritedProperties();
           m.ToTable("CardPayments");
      };

var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
var entityResult = 
     entityMethod.MakeGenericMethod(type)
          .Invoke(modelBuilder, new object[] { });

//invoke Map
entityResult.GetType().GetMethod("Map").Invoke(entityResult, new object[]{ mapLambda });

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