我正在使用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.DataServiceCollection
1[Api.Models.UserRoleSubProduct]' cannot be used for parameter of type System.Linq.IQueryable
類型的表達式1[Api.Models.UserRoleSubProduct]' cannot be used for parameter of type System.Linq.IQueryable
11[Api.Models.UserRoleSubProduct]' cannot be used for parameter of type System.Linq.IQueryable
[Microsoft.OData.Client.DataServiceCollection1[Api.Models.UserRoleSubProduct]]' of method 'Boolean Any[DataServiceCollection
1](System.Linq.IQueryable1[Microsoft.OData.Client.DataServiceCollection
1 [Api.Models.UserRoleSubProduct]],System.Linq.Expressions.Expression1[System.Func
2 [Microsoft] .OData.Client.DataServiceCollection`1 [Api.Models.UserRoleSubProduct],System.Boolean]])'
我想我足夠接近了。任何幫助表示讚賞
忽略冗餘的未使用的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
方法有重載 ,這對於“調用”靜態泛型擴展方法非常方便:
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)
);