LINQ To SQL 异常:本地序列不能用于查询运算符的 LINQ to SQL 实现,但包含运算符除外 [英] LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains operator

查看:22
本文介绍了LINQ To SQL 异常:本地序列不能用于查询运算符的 LINQ to SQL 实现,但包含运算符除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 LINQ To SQL 查询.其目的是获取一个字符串[] 搜索词并将这些词应用于 SQL 表上的一堆不同字段:

Consider this LINQ To SQL query. It's intention is to take a string[] of search terms and apply the terms to a bunch of different fields on the SQL table:

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();

引发异常:

本地序列不能在 LINQ to SQL 的查询运算符实现中使用,除了 Contains() 运算符

Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator

问题:为什么会引发这个异常,如何重写查询来避免这个异常?

Question: Why is this exception raised, and how can the query be rewritten to avoid this exception?

推荐答案

在您的查询中将 Any 的用法替换为 Contains.例如:

Replace the usages of Any with Contains in your query. eg:

searchTerms.Contains(c.Email)

这应该会得到您正在寻找的结果.它向后看,但它是正确的——它会为包含 searchTerms 中的所有元素的每个字段生成一个 IN 运算符.

This should get the result you're looking for. It looks backwards, but it's correct- it'll generate an IN operator for each field inside a Contains with all the elements in searchTerms.

AddressLine1 部分​​不会以这种方式工作 - 您必须自己使用

The AddressLine1 part won't work this way- you'll have to loop-generate the comparisons yourself with

c.addressLine1.Contains(...)

PredicateBuilder 之类的东西对此会有帮助.

Something like PredicateBuilder can be helpful for this.

这篇关于LINQ To SQL 异常:本地序列不能用于查询运算符的 LINQ to SQL 实现,但包含运算符除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆