Linq to entities-如何从多个搜索词转换为LIKE运算符

时间:2015-01-08 16:31:58

标签: sql linq-to-entities

我正在使用Linq to Entities过滤包含例如的所有课程名称(来自Sql Server数据库)数学式

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

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名称IN('math','drawing')

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您使用的是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,这将无效。

根据您可能效率不高的数据量而定,使用通配符创建存储过程可能更好。