2012-05-08 55 views
2

我试图动态生成一个表达式树查询查询有效地使用数据源。我试图复制查询的表达式树嵌套何在

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.LIN 'QBuilder.tests.Country]'不能用于返回类型'System.Boolean'

有没有人知道我在做什么错?

回答

0

我假设你想要的是一个lambda函数,赶上你Where通话的谓语部分。

A子句的类型必须是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)));