如何将实体 属性 作为 LINQ 表达式的参数传递?

How can I pass an entity property as a parameter of a LINQ Expression?

如何将实体 属性 作为 LINQ 表达式的参数传递?

public DropdownFilter(WhatTypeHere? ABC)
{
    // I want to store a selected property here
    // ABC must be a property of TEntity
    this.ABC = ABC;
}

// I want the class to encapsulate a LINQ query and just parametrize it with a property
public override IQueryable<TEntity> Filter(IQueryable<TEntity> filteredEntityCollection, string value)
{
    // ABC is a property of TEntity
    return filteredEntityCollection.Where(this.ABC == value);
}

我会这样使用它:

new DropdownFilter<Invoice>(invoice => invoice.SomeProperty);

我已经尝试过 Expression<Func<TEntity, string>> 种参数,但没有成功。它在抱怨

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

您必须手动构建 LINQ 表达式。首先,我将向您的 class 添加第二个通用参数,它将指定 属性 的类型和您将传递给过滤器的值的类型:

public class DropdownFilter<TEntity, TProperty>

接下来您应该将 属性 选择器表达式传递给此过滤器的构造函数 class:

private PropertyInfo propertyInfo;

public DropdownFilter(Expression<Func<TEntity, TProperty>> propertySelector)
{
    this.propertyInfo = (PropertyInfo)((MemberExpression)propertySelector.Body).Member;
}

最后,构建 lambda 表达式以根据指定的给定值过滤可查询 属性:

public IQueryable<TEntity> Filter(
   IQueryable<TEntity> filteredEntityCollection, TProperty value)
{
    var param = Expression.Parameter(typeof(TEntity), "p");

    var lambda = Expression.Lambda<Func<TEntity, bool>>(                
        Expression.Equal(
            Expression.Property(param, propertyInfo),
            Expression.Constant(value)
        ), param);

    return filteredEntityCollection.Where(lambda);
}

用法:

var filter = new DropdownFilter<Invoice, string>(i => i.ABC);
var result = filter(db.Invoices, "foo"); // strongly-typed parameter here

我会添加对传递给构造函数的 属性 选择器表达式的验证。您应该检查它是否是 MemberExpression。您可以验证 属性 类型以仅支持原始类型的属性。