LinQ LIKE运算符

时间:2012-09-18 14:20:23

标签: sql vb.net linq sql-like

我需要帮助在LINQ查询中使用普通的SQL LIKE %%运算符。

这是名为 Type 的行的数据(从没有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(“/”& catagory&“/”),查询就可以正常工作(返回4条记录)。但是,当我添加该部分时,无论我的操作符如何,它都会返回相同的记录。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

我使用了一些@Yaqub Ahmad代码来解决这个问题:

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