C# 如何在加入Linq时使用表达式获取动态谓词

C# 如何在加入Linq时使用表达式获取动态谓词,c#,linq,lambda,linq-to-entities,expression-trees,C#,Linq,Lambda,Linq To Entities,Expression Trees,我编写了一个静态方法,它将使用表达式api为不同类型的字段提供适当的谓词lambda static Func<T, bool> Process<T>(string type) { ParameterExpression parameter = Expression.Parameter(typeof(T)); Expression predicate = Expression.Constant(true); if (type == "Start")

我编写了一个静态方法,它将使用表达式api为不同类型的字段提供适当的谓词lambda

static Func<T, bool> Process<T>(string type)
{

    ParameterExpression parameter = Expression.Parameter(typeof(T));
    Expression predicate = Expression.Constant(true);
    if (type == "Start")
    {
        Expression prop = Expression.Property(parameter, type);
        Expression filter = Expression.LessThan(prop, Expression.Constant(DateTime.Now));
        predicate = Expression.AndAlso(predicate, filter);
    }
    //TODO: more if statments to come
    var lambda = Expression.Lambda<Func<T, bool>>(predicate, parameter);
    return lambda.Compile();
}
以上几行给出了编译时错误

Error   CS1929  'IQueryable<<anonymous type: MyClass m, Detail d>>' does not contain a definition for 'Where' and the best extension method overload 'EnumerableRowCollectionExtensions.Where<MyClass>(EnumerableRowCollection<MyClass>, Func<MyClass, bool>)' requires a receiver of type 'EnumerableRowCollection<MyClass>'
错误CS1929“IQueryable”不包含“Where”的定义,并且最佳扩展方法重载“EnumerableRowCollectionExtensions.Where(EnumerableRowCollection,Func)”需要“EnumerableRowCollection”类型的接收器
我知道,
.Where()
现在需要一个匿名类型,它有md,但不确定如何解决这个问题

我对ExpressionAPI相当陌生。不知道如何实现


我试图通过创建匿名类型变量来实现这一点,但这是一个变量,而不是将其传递给
Process()

的类型本身。您的
Process
方法的结果是
Where
子句,用于
MyClass
类型的对象,因此您不能使用它来过滤匿名对象
{m,d}
。而是在加入之前过滤:

var data = DbContext.MyClass.Where(del);                        
                            .Join(DbContext.Detail,
                                  mc => mc.Id,
                                  detail => detail.Id,
                                  (m, d) => new { m, d }
                             );

在将
MyClass
DateTime
进行比较的表达式中,这不是有效的
Func
,只能比较相关/正确的类型,在这里,您必须使用MyClass的属性来构建类似于Func的开始/结束,即DateTime,也可以将
Func
更改为
Expression
返回lambda.Compile()
返回lambda。否则,您的所有努力都将付诸东流,因为在检索整个
MyClass
表之后,查询将在内存中执行。
Error   CS1929  'IQueryable<<anonymous type: MyClass m, Detail d>>' does not contain a definition for 'Where' and the best extension method overload 'EnumerableRowCollectionExtensions.Where<MyClass>(EnumerableRowCollection<MyClass>, Func<MyClass, bool>)' requires a receiver of type 'EnumerableRowCollection<MyClass>'
var data = DbContext.MyClass.Where(del);                        
                            .Join(DbContext.Detail,
                                  mc => mc.Id,
                                  detail => detail.Id,
                                  (m, d) => new { m, d }
                             );