Linq2SQL to create a Like statement

I have the string "Word1 Word2" and I want to convert it to a query, for example, "Like"% Word1% Word2% ".

At the moment I have:

from t in Test where t.Field.Contains("Word1 Word2") 

How to do it in LINQ2SQL? I need to create two separate queries for this, can I write it in the same expression?

thanks in advance

+7
sql-like linq-to-sql
source share
3 answers
 from t in Test where SqlMethods.Like(t.Field, "%Word1%Word2%") select t 
+8
source share

Well, that would translate into

 LIKE "%Word1 Word2%" 

which is probably not the one you want ... If you write your query as follows:

 where t.Field.Contains("Word1") && t.Field.Contains("Word2") 

It will generate the following SQL:

 DECLARE @p0 VarChar(4) SET @p0 = '%ab%' DECLARE @p1 VarChar(4) SET @p1 = '%cd%' .... SELECT ... WHERE ([t0].[Field] LIKE @p0) AND ([t0].[Field] LIKE @p1) 
0
source share

As a job, perhaps this will be enough:

 from t in Test where t.Field.Contains("Word1") && t.Field.Contains("Word2") 

... with some post-filtering on the client side to ensure that word2 appears after word1.

0
source share

All Articles