简体   繁体   中英

Method calls on variable type retrieved through reflection

As part of an effort to create a workaround for an earlier problem , I have a list of Type on which I (in a perfect world) want to execute the following code:

foreach (Type entityType in entityTypes)
{
    modelBuilder.Entity<entityType>()
        .Map(m => m.Requires("Deleted").HasValue(false))
        .Ignore(m => m.Deleted);
}

Obviously, because we can't use variable types this way, I have to use reflection. So far, I am able to call up to the first method .Entity() :

foreach (Type entityType in entityTypes)
{
    var modelEntity = typeof (DbModelBuilder)
        .GetMethod("Entity")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelBuilder, null);
}

However, I still need to call .Map() and .Ignore() on modelEntity , which is of type EntityTypeConfiguration<T> . This is where my issue lies, because I do know (at runtime) that T is of type entityType , but I cannot simply call the following code:

foreach (Type entityType in entityTypes)
{
    var modelEntity = typeof (DbModelBuilder)
        .GetMethod("Entity")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelBuilder, null);

    var mappedEntity = typeof (EntityTypeConfiguration<entityType>)
        .GetMethod("Map")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelEntity, <parameters>);
}

Because I again have the same problem why I used reflection to call .Entity() in the first place. Can I again use reflection to call both methods, or can I use an other way to call them directly on modelEntity ?

One way to work around this issue is to make a generic method of your own to combine three calls into one, and use reflection to call your method, like this:

void LoopBody<T>() { // Give the method a better name
    modelBuilder.Entity<T>()
        .Map(m => m.Requires("Deleted").HasValue(false))
        .Ignore(m => m.Deleted);
}

Now you can call this method from your loop:

foreach (Type entityType in entityTypes) {
    GetType().GetMethod("LoopBody")
        .MakeGenericMethod(new[] { entityType })
        .Invoke(this, null);
}

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