考虑这个 LINQ To SQL 查询。它的目的是获取一个字符串 [] 搜索词并将这些词应用于 SQL 表上的一堆不同字段:
string[] searchTerms = new string[] {"hello","world","foo"};
List<Cust> = db.Custs.Where(c =>
searchTerms.Any(st => st.Equals(c.Email))
|| searchTerms.Any(st => st.Equals(c.FirstName))
|| searchTerms.Any(st => st.Equals(c.LastName))
|| searchTerms.Any(st => st.Equals(c.City))
|| searchTerms.Any(st => st.Equals(c.Postal))
|| searchTerms.Any(st => st.Equals(c.Phone))
|| searchTerms.Any(st => c.AddressLine1.Contains(st))
)
.ToList();
引发异常:
Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator
问题:
为什么会引发此异常,以及如何重写查询以避免此异常?
最佳答案
在您的查询中将 Any 的用法替换为 Contains。例如:
searchTerms.Contains(c.Email)
这应该会得到您正在寻找的结果。它向后看,但它是正确的——它会为包含 searchTerms 中的所有元素的每个字段生成一个 IN 运算符。
AddressLine1 部分不会以这种方式工作 - 您必须自己循环生成比较
c.addressLine1.Contains(...)
类似 PredicateBuilder可以对此有所帮助。
关于LINQ To SQL 异常 : Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1712105/