Kazu
Kazu

Reputation: 637

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?

Upvotes: 3

Views: 79

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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

Upvotes: 2

Related Questions