简体   繁体   English

如何在Linq中使用字符串数组All运算符

[英]How to Use String Array All Operator in Linq

My query is as follows: 我的查询如下:

string[] keys = txtSearch.Text.Split(' ');

var query = (from m in db.Messages
             join r in db.Recievers on m.Id equals r.Message_Id
             where (keys.All(k => (m.MessageText + m.Comments.Select(cmt => cmt.CommentText).ToString()).Contains(k)))
             select m.Id).Distinct();

I get the following error: 我收到以下错误:

Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator. 除Contains()运算符外,不能在查询运算器的LINQ to SQL实现中使用局部序列。

The problem is that your query can't be translated to SQL (or at least the provider is not programmed to do so). 问题是您的查询无法转换为SQL(或者至少没有对提供程序进行编程)。 If fact I don't know how that would query would look in SQL: "Give me all messages where all of these key words are contained in the text or comments" 如果实际上我不知道该查询将如何在SQL中查找:“给我所有消息,这些消息中的所有关键字都包含在文本或注释中”

My first thought is to to multiple requests, one for each key value: 我首先想到的是多个请求,每个键值一个:

List<int> allIDs = new List<int>();
foreach(string key in keys)
{
    var query = (from m in db.Messages
                 join r in db.Recievers on m.Id equals r.Message_Id
                 where m.MessageText.Contains(key) || m.Comments.Any(cmt => cmt.CommentText.Contains(key)
                 select m.Id).Distinct();
    allIds.AddRange(query);
}

but you may even need to search for messages and comments in separate queries. 但您甚至可能需要在单独的查询中搜索消息和评论。

obviously you'd prefer to do it in one query, but I don't see how that can be done in SQL without using cursors anyways. 显然,您宁愿在一个查询中执行此操作,但是我不知道在不使用游标的情况下如何在SQL中完成该操作。 If you can come up with a SQL statement that gives you the right results, then it may be easier to just call that SQL statement directly rather than trying to come up with a Linq statement that is compiled to equivalent SQL. 如果您可以提出一个可以为您提供正确结果的SQL语句,那么直接调用该SQL语句而不是尝试提供一个编译为等效SQL的Linq语句可能会更容易。

You can only use Array.Contains() in linq to SQL queries when using local collections. 使用本地集合时,只能在linq to SQL查询中使用Array.Contains()

You need to change your query based on this rule. 您需要根据此规则更改查询。

The All operator returns a boolean, it also determines if all elements satisfy a condition. All运算符返回一个布尔值,它还确定是否所有元素都满足条件。 As you're enumerating, as soon as a condition isn't met, the enumeration stops and returns a true or false. 在进行枚举时,只要不满足条件,枚举就会停止并返回true或false。

I believe you're expecting a Where functionality, return all the specified elements that satisfy a match on your search. 我相信您期望使用Where功能,返回所有符合搜索条件的指定元素。

I don't believe you're utilizing the query correctly. 我认为您没有正确使用查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM