For my needs, I tried to get the TPC (Table Per Concrete class) for my objects to call the MapInheritedProperties () function using Reflection.
So I want to make such calls for all my objects in the OnModelCreating method for DbContext
modelBuilder.Entity<MyEntity>().Map(o => o.MapInheritedProperties())
I tried to do this, but I was not able to create a delegate to the MapInheritedProperties () method because I get the following exception: it is impossible to bind to the target method because its signature or security transparency is incompatible with this delegate type.
foreach (var feEntityType in this.GetEntityTypes(onlyConcreteClasses: true))
{
var entityMethodInvoked = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(feEntityType).Invoke(modelBuilder, null);
ParameterExpression parameterExpression = ParameterExpression.Parameter(typeof(EntityMappingConfiguration<>).MakeGenericType(feEntityType), "o");
MethodInfo methodInfo = typeof(EntityMappingConfiguration<>).MakeGenericType(feEntityType).GetMethod("MapInheritedProperties", new Type[] { });
Expression mapInheritedPropertiesMethodExpression = Expression.Call(parameterExpression, methodInfo);
var mapMethod = typeof(EntityTypeConfiguration<>)
.MakeGenericType(feEntityType)
.GetMethods()
.Single(o => o.Name == "Map" && o.IsGenericMethod);
var mapMethodParameterType = typeof(Func<>).MakeGenericType(typeof(EntityMappingConfiguration<>).MakeGenericType(feEntityType));
var mapAction = methodInfo.CreateDelegate(mapMethodParameterType);
var mapMethodInvoked = mapMethod.MakeGenericMethod(feEntityType).Invoke(entityMethodInvoked, new[] { });
}
This is how I get my specific objects
protected IEnumerable<Type> GetEntityTypes(bool onlyConcreteClasses = false)
{
var entityTypes = typeof(EntitiesLocation).Assembly.GetTypes().Where(o => o.GetInterfaces().Contains(typeof(IEntity)));
foreach (var item in entitiesTypes)
{
if (onlyConcreteClasses && item.IsAbstract)
continue;
yield return item;
}
}
Any idea on how I can create a delegate? Or another way to call the MapInheritedProperties () method for all my objects without having to manually do it?