如何将PropertyInfo转换为属性表达式并使用它来调用泛型方法?

Pol*_*Pol 12 .net c# linq system.reflection

如何转换PropertyInfo为可用于调用StructuralTypeConfiguration<TStructuralType>.Ignore<TProperty>(Expression<Func<TStructuralType, TProperty>> propertyExpression)方法的属性表达式?

我试图用来Expression.Property()构造表达式,但是当我使用这个表达式作为propertyExpression参数时,我得到了以下错误:

The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly.

此错误可能是指TProperty类型参数,我不知道如何指定只有PropertyInfo.

我这样做是关于:使用Entity Framework的StructuralTypeConfiguration.Ignore()忽略所有属性,但指定set.

UPDATE

代码不起作用:

var propertyInfo = typeof(Foo).GetProperties()[0];
var expression = Expression.Default(typeof(Foo));
var expressionProperty = Expression.Property(expression, propertyInfo);
Ignore(expressionProperty);
Run Code Online (Sandbox Code Playgroud)

Ser*_*-Tm 22

var entityType = propertyInfo.DeclaringType;
var parameter = Expression.Parameter(entityType, "entity");
var property = Expression.Property(parameter, propertyInfo);
var funcType = typeof(Func<,>).MakeGenericType(entityType, propertyInfo.PropertyType);
var lambda = Expression.Lambda(funcType, property, parameter);

structureConfiguration.GetType()
   .GetMethod("Ignore")
   .MakeGenericMethod(propertyInfo.PropertyType)
   .Invoke(structureConfiguration, new[]{lambda});
Run Code Online (Sandbox Code Playgroud)