表情呼唤"任何"使用MethodCallExpression

时间:2017-11-08 16:59:59

标签: 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: 
 * {&& 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"))
    );

我试图调用Any的{​​{1}}方法。 表达式Enumerable代表entriesExpression(类型:x.DimensionSet.Entries

并且下一个参数代表一个常量ICollection<DimensionSetEntry>,其目的仅在于测试此时的调用,但此处我需要插入x => True

但是,调用此方法时,会发生以下错误:

  

为方法调用提供的参数数量不正确&#39;布尔值   任何[FUNC (d.DimensionValue.DimensionCode + "_" + d.DimensionValue.Value) == y 1 [System.Func`2 [EmployeePortal.Models.DimensionSetEntry,System.Boolean]])&#39;

1 个答案:

答案 0 :(得分:4)

Any()有两个重载;一个只需要IEnumerable<T>而另一个也需要一个lambda。

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

相关问题