为了满足我的需要,我试图通过使用反射调用MapInheritedProperties()来强制TPC(Table Per Concrete类)为我的实体。
所以我想要的是在 DbContext 的 OnModelCreate 方法中为我的所有实体进行这样的调用
modelBuilder.Entity<MyEntity>().Map(o => o.MapInheritedProperties())
我试图做的是这个,但我没有成功创建方法MapInheritedProperties()的委托,因为我得到以下异常:无法绑定到目标方法,因为它的签名或安全透明度与委托类型的签名或安全透明度不兼容。
foreach (var feEntityType in this.GetEntityTypes(onlyConcreteClasses: true))
{
// modelBuilder.Entity<Person>()
var entityMethodInvoked = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(feEntityType).Invoke(modelBuilder, null);
// o.MapInheritedProperties()
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);
// Method Map<T>(...)
var mapMethod = typeof(EntityTypeConfiguration<>)
.MakeGenericType(feEntityType)
.GetMethods()
.Single(o => o.Name == "Map" && o.IsGenericMethod);
// Func<EntityMappingConfiguration<MonEntite>>
var mapMethodParameterType = typeof(Func<>).MakeGenericType(typeof(EntityMappingConfiguration<>).MakeGenericType(feEntityType));
var mapAction = methodInfo.CreateDelegate(mapMethodParameterType); // <== DOESN'T WORK ==> Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
var mapMethodInvoked = mapMethod.MakeGenericMethod(feEntityType).Invoke(entityMethodInvoked, new[] { /* PARAMETER */ });
}
这是我如何获得具体实体的
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;
}
}
关于如何创建委托的任何想法?或者另一种方法可以为我的所有实体调用方法 MapInheritedProperties() 而无需手动制作?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//do whatever to get your entity Types
var entityTypes = typeof(EntitiesLocation).Assembly.GetTypes()
.Where(x => x.IsClass && !x.IsAbstract && x.GetInterfaces()
.Any(i => i == typeof(IEntity)));
foreach (var entityType in entityTypes)
{
GetType().GetMethod(nameof(MapInheritedProperties))
.MakeGenericMethod(entityType)
.Invoke(this, new object[] { modelBuilder });
}
}
public void MapInheritedProperties<TEntity>(DbModelBuilder modelBuilder) where TEntity : class
{
modelBuilder.Entity<TEntity>().Map(m => m.MapInheritedProperties());
}