[英]LinQ LIKE operator
I need help with using a normal SQL LIKE %% operator within a LINQ query. 我需要帮助在LINQ查询中使用普通的SQL LIKE %%运算符。
This is the data for row called Type (thats returned from the normal query without the like operator): 这是名为Type的行的数据(从没有like运算符的普通查询返回的数据):
Independent Contractor
Lease Program
Teams
Teams interested
And this is my (attempted) LINQ query: 这是我的(尝试过的)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
If i leave out the And hl.Type.Contains("/" & catagory & "/") the query works just fine (returns 4 records). 如果我省略了和hl.Type.Contains(“/”&catagory&“/”) ,查询工作正常(返回4条记录)。 But when i add that part it returns the same records regardless of my like operator. 但是,当我添加该部分时,它返回相同的记录,而不管我喜欢的运算符。
Instead of 代替
hl.Type.Contains("/" & catagory & "/")
try this: 尝试这个:
SqlMethods.Like(hl.Type, "%"& category &"%")
EDIT : 编辑 :
I am not good with VB.Net syntax. 我对VB.Net语法不太满意。
EDIT: 编辑:
Actually the result sql of your LINQ query becomes: 实际上你的LINQ查询的结果sql变成:
SELECT *
FROM myTable
WHERE State = state_abbr OR
AlternateLocation LIKE state_abbr AND
Type LIKE category
BUT you need this i guess: 但我猜你需要这个:
SELECT *
FROM myTable
WHERE (State = state_abbr OR
AlternateLocation LIKE state_abbr) AND
Type LIKE category
Try this: 尝试这个:
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()
I figured it out using some of @Yaqub Ahmad code: 我用@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.