为 LINQ 查询使用表达式树构建 Any()

Rey*_*gle 4 c# linq expression-trees

我正在使用 System.Linq.Expressions.Expression 类动态构建 SQL“Any”子句

我可以这样做

Expression<Func<User, Lead, bool>> predicate = (user, lead) => user.UserRoleSubProducts.Any(x => x.SubProductID == lead.SubProductID);
Run Code Online (Sandbox Code Playgroud)

但是我无法使用表达式树来实现这一点。

我在下面试过

var param1 = Expression.Parameter(typeof(User), "user");
var property1 = Expression.Property(param1, "UserRoleSubProducts");
var exp1 = Expression.Lambda(property1, new[] { param1 });

var param2 = Expression.Parameter(typeof(Lead), "lead");
var property2 = Expression.Property(param2, "SubProductID");
var exp2 = Expression.Lambda(property2, new[] { param2 });

var param3 = Expression.Parameter(property1.Type.GetProperty("Item").PropertyType, "x");
var property3 = Expression.Property(param3, "SubProductID");
var exp3 = Expression.Lambda(property3, new[] { param3 });

var equality = Expression.Equal(property2, property3);

var any = typeof(Queryable).GetMethods().Where(m => m.Name == "Any").Single(m => m.GetParameters().Length == 2).MakeGenericMethod(property1.Type);

var expression = Expression.Call(null, any, property1, equality);
Run Code Online (Sandbox Code Playgroud)

但是得到

'Microsoft.OData.Client.DataServiceCollection 1[Api.Models.UserRoleSubProduct]' cannot be used for parameter of type System.Linq.IQueryable1[Microsoft.OData.Client.DataServiceCollection 1[Api.Models.UserRoleSubProduct]]' of method 'Boolean Any[DataServiceCollection1](System.Linq.IQueryable 1[Microsoft.OData.Client.DataServiceCollection1[Api.Models.UserRoleSubProduct]], System.Linq.Expressions.Expression 1[System.Func2[Microsoft.OData .Client.DataServiceCollection`1[Api.Models.UserRoleSubProduct],System.Boolean]])'

我想我已经足够接近了。任何帮助表示赞赏

Iva*_*oev 5

忽略多余的未使用的 lambda 表达式,问题出在最后 2 行。

首先,您使用了错误的泛型类型 ( MakeGenericMethod(property1.Type)),而正确的类型基本上是x这里的参数类型

.Any(x => x.SubProductID == lead.SubProductID)
Run Code Online (Sandbox Code Playgroud)

=>

.Any<T>((T x) => ...)
Run Code Online (Sandbox Code Playgroud)

映射到param3.Type您的代码中。

其次, the 的第二个参数Any必须是 lambda 表达式(不仅仅是equality代码中的)。

第三,由于user.UserRoleSubProducts最有可能是一个集合类型,您应该发出对Enumerable.Any而不是 的调用Queryable.Any

Expression.Call方法具有重载,这对于“调用”静态泛型扩展方法非常方便:

public static MethodCallExpression Call(
    Type type,
    string methodName,
    Type[] typeArguments,
    params Expression[] arguments
)
Run Code Online (Sandbox Code Playgroud)

所以最后两行可以替换为:

var anyCall = Expression.Call(
    typeof(Enumerable), nameof(Enumerable.Any), new Type[] { param3.Type },
    property1, Expression.Lambda(equality, param3)
);
Run Code Online (Sandbox Code Playgroud)