2

我正在尝试动态构建一个表达式树,该树使用 in 查询有效地查询数据源。我试图复制的查询是

Countries.Where(y => Countries
                         .Where(x =>
                             x.CountryLanguage.Any(b => b.CountryID == 73) &&
                             x.CountryLanguage.Any(b => b.CountryID == 150))
                         .Select(z => z.ShortCode)
                         .Contains(y.ShortCode))

我已经尝试了很多方法,但这是我最近的尝试:

public void AddContainsWhereClause(IQueryable<T> objectSet, string predicateIdentifier)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), predicateIdentifier);

    Expression expInner = Expression.Call(
        typeof(Queryable),
        "Where",
        new Type[] { typeof(T) },
        objectSet.Expression,
        Expression.Lambda<Func<T, bool>>(rootExperession, resultExpression));

    Expression expOuter = Expression.Call(
        typeof(Queryable),
        "Where",
        new Type[] { typeof(T) },
        objectSet.Expression,
        Expression.Lambda<Func<T, bool>>(expInner, pe));

}

NB rootExpression 是:

x => x.CountryLanguage.Any(b => b.CountryID == 73) &&
     x.CountryLanguage.Any(b => b.CountryID == 150)

但这会返回:

[ApplicationFramework.LINQBuilder.tests.Country]'不能用于返回类型'System.Boolean'

有谁知道我做错了什么?

4

1 回答 1

0

我假设你想要的是一个 lambda 函数来模拟你的Where调用的谓词组件。

where 子句需要是 type Func<TSource, bool>,但您正在调用Queryable.Where,它实际上返回一个IEnumerable.

沿着表达式树路径(可能非常复杂且难以维护),您真正的问题是否只是您需要选择支持所提供国家列表语言的国家列表?

int[] requiredCountryIds = {73, 150};

// Select countries which contain all required country IDs in their CountryLanguage set
var resultSet =
    countries.Where(
        y => requiredCountryIds.All(requiredCountryId => y.CountryLanguage.Any(b => b.CountryId == requiredCountryId)));
于 2012-06-07T01:44:58.157 回答