vendredi 9 janvier 2015

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?






Aucun commentaire:

Enregistrer un commentaire