如何使用反射来调用DbModelBuilder.Entity<;T>;.忽略(x=>;x.Property)

本文关键字:gt Property 忽略 lt 反射 何使用 调用 Entity DbModelBuilder | 更新日期: 2023-09-27 17:58:56

我正在根据poco类上的属性动态执行流畅的映射,并且.Property的情况运行良好,但在尝试运行.Ignore()方法时失败了:

private void AddEntities(DbModelBuilder modelBuilder)
{
    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
    foreach (var entityType in EntityBaseTypes)
    {
        dynamic entityConfiguration = entityMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, new object[] { });
        foreach (PropertyInfo propertyInfo in entityType.GetProperties().Where(x => x.CanWrite))
        {
            foreach (var attribute in propertyInfo.GetCustomAttributes())
            {
                LambdaExpression propertyLambda = PropertyGetLambda(entityType, propertyInfo.Name, typeof(string));
                string attributeName = attribute.GetType().Name;
                if (attributeName == "NotMappedAttribute")
                {
                    MethodInfo ignoreMethod = (MethodInfo)entityConfiguration.GetType().GetMethod("Ignore");                            
//BLOWS UP HERE: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true
                    ignoreMethod.Invoke(entityConfiguration, new[] { propertyLambda });
                }
                else if (attributeName == "ColumnAttribute")
                {
                    dynamic column = attribute;
                    var propertyMethod = entityConfiguration.GetType().GetMethod("Property", new Type[] { propertyLambda.GetType() });
                    var entityProperty = (PrimitivePropertyConfiguration)propertyMethod.Invoke(entityConfiguration, new[] { propertyLambda });
//WORKS FINE:
                    entityProperty.HasColumnName(column.Name);
                }
            }
        }
    }
}

我认为.Ignore()方法参数所需的类型不同。这是我试图调用的方法:.Ignore()

public void Ignore<TProperty>(
    Expression<Func<TStructuralType, TProperty>> propertyExpression
)

如何使用反射来调用DbModelBuilder.Entity<;T>;.忽略(x=>;x.Property)

我认为您需要使用获得Ignore方法的MemberInfo

MethodInfo ignoreMethod = typeof(StructuralTypeConfiguration<>)
    .MakeGenericType(entityType)
    .GetMethod("Ignore")
    .MakeGenericMethod(propertyInfo.PropertyType);

Ignore是一个具有与Expression的属性类型相对应的泛型参数的方法,因此在尝试调用它之前需要提供属性类型。