The method calls the type of the variable obtained by reflection

As part of an effort to create a workaround for an earlier problem , I have a list 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 cannot use variable types in this way, I have to use reflection. So far, I can call 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 the type EntityTypeConfiguration<T>

. That's where my problem is, because I know (at runtime) what the T

type is entityType

, but I can't just 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 have the same problem again, why I used reflection to call .Entity()

in the first place. Can I use reflection again to call both methods, or can I use another way to call them directly on modelEntity

?

+3


source to share


1 answer


One way to get around this problem is to create your own generic method to combine the three calls into one and use reflection to call your method, for example:

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 within the loop:

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

      

+2


source







All Articles