简体   繁体   English

使用Linq to Entities执行字符串搜索

[英]Perform string search with Linq to Entities

I want to enable this function in Linq to Entities (so the filtering happens on the SQL Server)? 我想在Linq to Entities中启用此功能(因此过滤发生在SQL Server上)?

public static bool ContainsAny(this string source, StringComparison comparison,
                               IEnumerable<string> searchTerms)
{
  return searchTerms.Any(searchTerm => source.Contains(searchTerm, comparison));
}

My goal is search a table and limit the result by filtering a certain column with the above function, ie GetContacts().Where(c => c.FullName.ContainAny(searchTerm)) . 我的目标是搜索表并通过使用上述函数过滤某个列来限制结果,即GetContacts().Where(c => c.FullName.ContainAny(searchTerm))

First, it's tricky (if possible which I don't know) to use StringComprison in Expressions and expect Linq 2 Entities to translate it to correct Sql statements. 首先,在Expressions中使用StringComprison并期望Linq 2实体将其转换为正确的Sql语句是棘手的(如果可能的话,我不知道)。

Second, it's tricky to use a custom function like your ContainsAny in an Expression too. 其次,在Expression中使用像ContainsAny这样的自定义函数也很棘手。

So if I were you, the simple solution is: 如果我是你,简单的解决方案是:

GetContacts().Where(c => searchTerms.Any(term => c.FullName.Contains(term)))

which should work in EF4. 哪个应该在EF4中工作。

Take a look at a nuget package I have created 看看我创建的nuget包

http://www.nuget.org/packages/NinjaNye.SearchExtensions http://www.nuget.org/packages/NinjaNye.SearchExtensions

This will enable the following (and more) which will return results where the search term appears in property specified 这将启用以下(以及更多),这将返回搜索项出现在指定属性中的结果

var result = GetContacts().Search("searchTerm", c => c.FullName);

For searching multiple terms you can do the following: 要搜索多个术语,您可以执行以下操作:

var result = GetContacts().Search(searchTerms, c => c.FullName);

The above will return results where any search term appears in the property 以上将返回任何搜索词出现在属性中的结果

This builds up an expression tree which performs the search on the database not in memory, so only matching results are returned form the server. 这会构建一个表达式树,它对数据库而不是内存执行搜索,因此只从服务器返回匹配的结果。

For more information take a look at the projects GitHub page or my blog posts 有关更多信息,请查看项目GitHub页面或我的博客文章

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

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