【发布时间】:2017-11-08 16:59:58
【问题描述】:
我正在尝试实现以下代码:
db.Invoices.Where(x => Dimensions.All(y => x.DimensionSet.Entries.Any(dim => (d.DimensionValue.DimensionCode + "_" + d.DimensionValue.Value) == y))
我尝试过的:
/* Dimensions Logic
* Copy the following logic:
* {&& Dimensions.All(y => x.DimensionSet.Entries.Any(d => (d.DimensionValue.DimensionCode + "_" + d.DimensionValue.Value) == y))}
*/
/* Get expression of the nested property Func<string, bool> to imitate the second argument of `Dimensions.All` */
Expression entriesExpression = Expression.Property(body, "Entries");
/* Get expression of the current Dimensions property */
Expression dimensionsExpression = Expression.Constant(Dimensions);
Type dimensionsAllType = typeof(Func<,>).MakeGenericType(typeof(string), typeof(bool));
Type innerAnyType = typeof(Func<,>).MakeGenericType(typeof(DimensionSetEntry), typeof(bool));
/* Get the `All` method that may be used in LINQ2SQL
* Making a generic method will guarantee that the given method
* will match with the needed parameters.
* Like it was a "real" linq call.
*/
MethodInfo methodAll =
typeof(Enumerable)
.GetMethods()
.FirstOrDefault(x => x.Name == "All")
.MakeGenericMethod(dimensionsAllType);
MethodInfo methodAny =
typeof(Enumerable)
.GetMethods()
.FirstOrDefault(x => x.Name == "Any")
.MakeGenericMethod(innerAnyType);
MethodCallExpression call_Any = Expression.Call(
null,
methodAny,
entriesExpression,
Expression.Lambda(Expression.Constant(true), Expression.Parameter(typeof(DimensionSetEntry), "y"))
);
MethodCallExpression call_All = Expression.Call(
null,
methodAll,
dimensionsExpression,
call_Any
);
现在,我只在表达式调用上苦苦挣扎。
MethodCallExpression call_Any = Expression.Call(
null,
methodAny,
entriesExpression,
Expression.Lambda(Expression.Constant(true), Expression.Parameter(typeof(DimensionSetEntry), "y"))
);
这里我试图调用Enumerable 的Any 方法。
表达式entriesExpression代表x.DimensionSet.Entries(类型:ICollection<DimensionSetEntry>)
并且下一个参数代表一个常量x => True,目前仅用于测试调用,但在这里我需要插入(d.DimensionValue.DimensionCode + "_" + d.DimensionValue.Value) == y。
但是,调用这个的时候,出现如下错误:
为调用“Boolean”方法提供的参数数量不正确 任意[Func
2](System.Collections.Generic.IEnumerable1[System.Func`2[EmployeePortal.Models.DimensionSetEntry,System.Boolean]])'
【问题讨论】:
标签: c# .net lambda expression