为LINQ查询构建具有表达式树的Any()

问题描述 投票:2回答:1

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

我可以这样做

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

但我无法使用Expression Tree实现这一目标。

我试过下面的

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

但是得到

类型'Microsoft.OData.Client.DataServiceCollection1[Api.Models.UserRoleSubProduct]' cannot be used for parameter of type System.Linq.IQueryable1 [Microsoft.OData.Client.DataServiceCollection1[Api.Models.UserRoleSubProduct]]' of method 'Boolean Any[DataServiceCollection1](System.Linq.IQueryable1[Microsoft.OData.Client.DataServiceCollection1 [Api.Models.UserRoleSubProduct]],System.Linq.Expressions.Expression1[System.Func2 [Microsoft.OData.Client.DataServiceCollection]的表达式`1 [Api.Models.UserRoleSubProduct],System.Boolean]])”

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

c# linq expression-trees
1个回答
4
投票

忽略冗余的未使用的lambda表达式,问题在于最后两行。

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

.Any(x => x.SubProductID == lead.SubProductID)

=>

.Any<T>((T x) => ...)

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

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

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

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

public static MethodCallExpression Call(
    Type type,
    string methodName,
    Type[] typeArguments,
    params Expression[] arguments
)

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

var anyCall = Expression.Call(
    typeof(Enumerable), nameof(Enumerable.Any), new Type[] { param3.Type },
    property1, Expression.Lambda(equality, param3)
);
© www.soinside.com 2019 - 2024. All rights reserved.