请参阅以下代码:
var source = Peoples.AsQueryable();
IQueryable<People> p;
p = source.Where( x => false);
p = p.Concat(source.Where( x => x.FirstName == "DAVID"));
p = p.Concat(source.Where(x => x.City_id == 3));
p.Dump(); //I use linqpad but it does not matter now
这段代码工作,linq2sql产品一个sql语句(带三个qouery和UNION ALL
)。
现在是相同的代码,表面上完全相同的程序,在另一个变体中,抛出NotSupportedException:
var q = new IQueryableUnderstand<People>(Peoples.AsQueryable());
q.AddToList(x => x.City_id == 3);
q.AddToList(x => x.FirstName == "Dave");
q.Results().Dump();
IQueryableUnderstand Class:
class IQueryableUnderstand<T>
{
IQueryable<T> _source;
IQueryable<T> combin;
public IQueryableUnderstand(IQueryable<T> source)
{
_source = source;
combin = _source.Where(s => false);
}
public void AddToList(Func<T, bool> predicate) => combin = combin.Concat(_source.Where(predicate));
public IQueryable<T> Results() => combin;
}
LINQ To SQL异常:除了Contains运算符之外,本地序列不能用于查询运算符的LINQ to SQL实现
我觉得愚蠢,有什么区别?
答案 0 :(得分:1)
您的AddToList()
方法接受Func<T, bool>
谓词。参数类型不正确。如果应用于您的查询,它会将其转换为Linq-To-Objects查询。 IQueryable<TSource>
需要表达式,而不是委托。
更改您的方法签名:
public void AddToList(Expression<Func<T, bool>> predicate) =>
combin = combin.Concat(_source.Where(predicate));