【发布时间】:2019-12-07 00:00:27
【问题描述】:
我有一个应用程序,它在单击搜索按钮时从数据库中提取元素。我需要更新它,以便可以在字符串中找到具有特定 Substring 的元素,正好有 6 个位置。例如,我需要通过在第 6 位和第 7 位查找 33 来找到 111-2233-44-555。我的第一直觉是为字符串类创建一个扩展方法,这样我就可以这样说:
Dim example As String = "111-2233-44-555"
If example.HasYear(33) Then
'Do Something'
End If
这很完美。这是我做的方法:
Public Module StringExtensionMethods
''' <summary>
''' Finds the year in a competition number of format XXX-XXXX-XX-XXX
''' </summary>
''' <param name="pstrCompNum">The competition number to find the year in</param>
<Extension()>
Public Function HasYear(ByVal pstrCompNum As String, ByVal pstrCompYear As String) As Boolean
Try
Dim testString As String = pstrCompNum
Debug.Print(testString)
Dim testSubstring As String = testString.Substring(6, 2)
If testSubstring.Equals(pstrCompYear) Then
Return True
End If
Return False
Catch ex As Exception
Throw ex
End Try
End Function
End Module
但是当我尝试在SQL 查询中使用此方法时出现问题。没错,因为HasYear() 与SQL 没有任何关系。这是我要执行的查询:
Dim o = From c In myContext.Competitions.Include("CodeJusticeBranches").Include("CodeJusticeLocations").Include("CodeCompetitionTypes").Include("CodePositionTypes").Include("CompetitionPositions") _
Where (pstrCompNum Is Nothing OrElse c.comp_number = pstrCompNum) _
And (pstrCompYear Is Nothing OrElse c.comp_number.HasYear(strYear) = True) _
And (pstrCompTypeId Is Nothing OrElse c.CodeCompetitionTypes.code_ct_id = CInt(pstrCompTypeId)) _
And (pstrBranchId Is Nothing OrElse c.CodeJusticeBranches.code_branch_id = CInt(pstrBranchId)) _
And (pstrPosTypeId Is Nothing OrElse c.CodePositionTypes.code_pos_type_id = CInt(pstrPosTypeId)) _
Order By c.comp_number _
Select c
我收到错误 LINQ to Entities 无法识别方法 'Boolean HasYear (System.String, System.String)' 方法,并且此方法无法转换为存储表达式。
所以我正在寻找的本质上是一种制作可用于SQL 查询的扩展方法的方法。有什么想法吗?
【问题讨论】:
-
许多框架方法在 LINQ 中不起作用,因为 SQL 服务器不支持它们。您应该只包含查询中支持的方法,然后输入
ToList()来执行查询,然后使用您不支持的方法过滤结果数据。 -
SubString应该可以翻译成 SQL,所以你根本不能使用HasYear函数。 -
好主意,我试过了,效果很好。谢谢。
标签: sql vb.net visual-studio