C# 表达式调用";任何;使用MethodCallExpression

C# 表达式调用";任何;使用MethodCallExpression,c#,.net,lambda,expression,C#,.net,Lambda,Expression,我正在尝试实现以下代码: 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: * {&& Dimensi

我正在尝试实现以下代码:

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
);
在这里,我试图调用
可枚举的
方法的
任何
方法。
表达式
entrieexpression
表示
x.DimensionSet.Entries
(类型:
ICollection

下一个参数表示一个常量
x=>True
,目前只用于测试调用,但这里我需要插入
(d.DimensionValue.DimensionCode+“”+d.DimensionValue.Value)==y

但是,调用此函数时,会发生以下错误:

为调用方法“Boolean”提供的参数数量不正确 任意[Func
2](System.Collections.Generic.IEnumerable
1[System.Func`2[EmployeePortal.Models.DimensionSetEntry,System.Boolean]]

Any()
有两个重载;一个只接受一个
IEnumerable
,另一个也接受一个lambda

您的
methodAny
变量可能包含第一个变量。您需要更改该变量以查找带有两个参数的重载

MethodCallExpression call_Any = Expression.Call(
        null,
        methodAny,
        entriesExpression,
        Expression.Lambda(Expression.Constant(true), Expression.Parameter(typeof(DimensionSetEntry), "y"))
    );