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

标签 c# .net 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 .

我这样做是为了:Use Entity Framework's StructuralTypeConfiguration.Ignore() to Ignore all properties but specified set .

更新

无效的代码:

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

最佳答案

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});

关于c# - 如何将 PropertyInfo 转换为属性表达式并使用它来调用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9621736/

相关文章:

c# - 无法从程序集 'System.Environment' 加载类型 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

c# - 如何允许用户编辑 Program Files 下的 App.config 是记事本或其他编辑器?

c# - 重用 LINQ 选择功能

c# - 如何在 .net Framework 4.6 上启用 Vector.IsHardwareAccelerated?

c# - 如何编写一个 C# 方法来接受未知类型的注入(inject)依赖项?

c# - "Division by constant zero"?微软视觉 C#

c# - 有没有办法将 IEnumerable 转换为 XElements 的集合?

c# - 如何创建可在 IronPython 中处理的 C# 事件处理程序?

c# - 如何仅在发布版本上请求管理员权限?

c# - 通过 LINQ 使用通用列表中的值格式化字符串