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

Shi*_*mmy 4 .net c# linq string linq-to-entities

我想在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));
}
Run Code Online (Sandbox Code Playgroud)

我的目标是搜索表并通过使用上述函数过滤某个列来限制结果,即GetContacts().Where(c => c.FullName.ContainAny(searchTerm)).

dee*_*hao 6

首先,在Expressions中使用StringComprison并期望Linq 2实体将其转换为正确的Sql语句是棘手的(如果可能的话,我不知道).

其次,在Expression中使用像ContainsAny这样的自定义函数也很棘手.

如果我是你,简单的解决方案是:

GetContacts().Where(c => searchTerms.Any(term => c.FullName.Contains(term)))
Run Code Online (Sandbox Code Playgroud)

哪个应该在EF4中工作.