可以按如下方式实现:
Expression<Func<User, Lead, bool>> predicate = (user, lead) => user.UserRoleSubProducts.Any(x => x.SubProductID == lead.SubProductID);
但我无法使用表达式树来实现这一点。
我已经尝试了以下方法:
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]'的表达式不能用于类型为'System.Linq.IQueryable
1[Microsoft.OData.Client.DataServiceCollection1[Api.Models.UserRoleSubProduct]]'的参数。方法为'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]])'
我认为我已经接近解决方案了,非常感谢任何帮助。