0

我需要在 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

如果我省略And hl.Type.Contains("/" & catagory & "/")查询工作得很好(返回 4 条记录)。但是,当我添加该部分时,无论我的 like 运算符如何,它都会返回相同的记录。

4

2 回答 2

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()
于 2012-09-18T14:30:21.840 回答
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
于 2012-09-18T15:05:38.943 回答