2012-09-18 63 views
0

我需要與使用LINQ查詢中的正常SQL LIKE操作%%幫助。LinQ在LIKE操作

這是行的數據稱爲類型(多數民衆贊成在正常的查詢返回不喜歡運營商):

Independent Contractor 
Lease Program 
Teams 
Teams interested 

這是我(未遂)LINQ查詢:

Public Shared Function SelectActiveByState(
    ByVal state_abbr As String, 
    ByVal catagory As String) As List(Of theLocations) 

    Dim db As New MasterData 
    db.CommandTimeout = 240 

    Try    
     Return (_ 
      From hl In db.Locations _ 
      Where hl.Active = True _ 
      And (_ 
       hl.State = state_abbr Or _ 
       hl.AlternateLocation.Contains(state_abbr) And _ 
       hl.Type.Contains("/" & catagory & "/") _ 
      ) _ 
      Order By hl.Type Select hl).ToList() 

    Catch ex As Exception 
     Return Nothing 
    End Try 
End Function 

如果我遺漏了和hl.Type.Contains(「/」&類別&「/」)查詢工作得很好(返回4條記錄)。但是當我添加該部分時,無論我的操作符如何,它都會返回相同的記錄。

+0

你真的有兩個字段'_Type'和'Type'?你感到困惑嗎? –

+0

剛糾正@RB。查看更新的OP。 – StealthRT

回答

2

而不是

hl.Type.Contains("/" & catagory & "/") 

試試這個:

SqlMethods.Like(hl.Type, "%"& category &"%") 

編輯

我不擅長與VB.Net語法。

編輯:

其實你的LINQ查詢的結果SQL變爲:

SELECT * 
FROM myTable 
WHERE State = state_abbr OR 
     AlternateLocation LIKE state_abbr AND 
     Type LIKE category 

,但你需要這個,我想:

SELECT * 
FROM myTable 
WHERE (State = state_abbr OR 
     AlternateLocation LIKE state_abbr) AND 
     Type LIKE category 

試試這個:

Return (_ 
    From hl In db.Locations _ 
    Where hl.Active = True _ 
    And (_ 
     (hl.State = state_abbr Or _ 
     hl.AlternateLocation.Contains(state_abbr)) And _ 
     SqlMethods.Like(hl.Type, "%"& category &"%") _ 
    ) _ 
    Order By hl.Type Select hl).ToList() 
+0

** ** SqlMethods.Like似乎並沒有成爲我的項目的一部分,以便能夠使用。 – StealthRT

+0

** ** System.Data.Linq.SqlClient.SqlMethods.Like – StealthRT

+0

仍然得到同樣的結果。所有記錄,而不是2. – StealthRT

0

我想通了使用某些@Yaqub艾哈邁德代碼:

Public Shared Function SelectActiveByState(
    ByVal state_abbr As String, 
    ByVal catagory As String) As List(Of theLocations) 

    Dim db As New MasterData 
    db.CommandTimeout = 240 

    Try    
     Return (_ 
      From hl In db.Locations _ 
      Where hl.Active = True _ 
      And (_ 
       (hl.State = state_abbr Or _ 
       hl.AlternateLocation.Contains(state_abbr)) And _ 
       System.Data.Linq.SqlClient.SqlMethods.Like(hl.Type, "%" & category & "%") _ 
      ) _ 
      Order By hl.Type Select hl).ToList() 

    Catch ex As Exception 
     Return Nothing 
    End Try 
End Function