2017年2月23日 星期四

【C#】Exception when trying Where a PredicateBuilder predicate

Cannot convert expression type 'System.Linq.Expressions.Expression>' to return type 'System.Func'

無法從 'System.Linq.Expressions.Expression>' 轉換為 'System.Func'

第二次碰到這個問題還是傻掉,白白浪費快一小,還是寫一下,簡單的說 IEnumerable 的 Where 是不能串 PredicateBuilder predicate 的,必須是 IQueryable,所以
IEnumerable filteredMembers = _members.Where(something);
var orPred = PredicateBuilder.True();
foreach (Condition condition in target.ValidMemberConditions)
{
    orPred = orPred.Or(m => m.BusinessCode == condition.BusinessCode &&
        m.MemberTypeID == condition.MemberType);
}
filteredMembers = filteredMembers.Where(orPred); // X
這樣不行,但
IQueryable filteredMembers = _members.Where(something).AsQueryable(); // modified
var orPred = PredicateBuilder.True();
foreach (Condition condition in target.ValidMemberConditions)
{
    orPred = orPred.Or(m => m.BusinessCode == condition.BusinessCode &&
        m.MemberTypeID == condition.MemberType);
}
filteredMembers = filteredMembers.Where(orPred); // O
這樣可以

沒有留言:

張貼留言