Linq to entities - 如何从多个搜索词翻译成 LIKE 运算符

Linq to entities- How to translate to LIKE operator from multiple search terms

我正在使用 Linq to Entities 来过滤所有课程名称(来自 Sql 服务器数据库),例如数学.

只要一学期,就很容易了。我只需要有以下代码。

filteredCourses = from f in filteredCourses
                      where f.Name.Contains("math") 
                      select f;

这在 SQL 中被翻译成:WHERE name LIKE '%math%'。而且很好!

但是如果我有一个术语列表,例如:

var query = new string[] { "math", "drawing" };

我试过这个代码

filteredCourses = from f in filteredCourses
 where query.Contains(f.Name)
 select f;

但它转换为 WHERE name IN ('math', 'drawing')

我怎么能这样做它在 SQL 中被翻译成:

WHERE name LIKE '%math%' OR name LIKE '%drawing%'

谢谢!

如果您使用的是Entity Framework,您可以这样做:

filteredCourses = from f in filteredCourses 
              where query.Any(q=>f.Name.Contains(q)) select f;

它将生成一个 SQL 接近于此的查询:

"SELECT * FROM [dbo].[filteredCourses ] AS [Extent1]
WHERE  EXISTS (SELECT   1 AS [C1]   FROM  
(SELECT     N'SEARCH_QUERY_1' AS [C1]          
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]     
UNION ALL            
SELECT N'SEARCH_QUERY_2' AS [C1] FROM  ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]           
WHERE ( CAST(CHARINDEX([UnionAll1].[C1], [Extent1].[Name]) AS int)) > 0)"

如果您使用 Linq to SQL,这将不起作用。

根据您拥有的数据量,这可能效率不高,您最好使用通配符创建存储过程