简体   繁体   中英

Using SQL Wildcards with LINQ

I have a question about using LINQ to access a Database and trying to make use of it's version of accessing the LIKE comparison operator.

I know that LINQ has .Contains() , .StartsWith() , and .EndsWith() as comparison methods. However I am wondering if there is a way to programatically imcorporate SQL Wildcards into a LINQ statement without explicitly using these query operators. Let me explain my situation.

I am writing a program that accesses a database, and part of the program is a search window which the user can use to help them find specific database data. I would like to try and incorporate SQL Wildcards into the textbox fields for these search pages.

For example if a user enters the input 17% I'd want the program to check for anything in that specific column that starts with a 17 . The same is true with %17 and 17 where I'd want it to search for columns that end with, and contain the values.

Currently, this is the code I have for my search method:

Public Function Data_Search(sData As List(Of String), DB As CustomDataContext) As DataGridView
    Dim gridData As New DataGridView
    Dim query = From p In DB.Parts
                Select p.Part_Number, p.Part_Description, p.Supplier.Supplier_Name
    for i = 0 To sData.Count - 1
        If Not sData(i).ToString() = "" Then
            Select Case i
                Case 0
                    Dim partNum As String = sData(i).ToString()
                    query = query.Where(Function(x) x.Part_Number.Contains(partNum))
                Case 1
                    Dim description As String = sData(i).ToString()
                    query = query.Where(Function(x) x.Part_Description.Contains(description))
                Case 2
                    Dim supp As String = sData(i).ToString()
                    query = query.Where(Function(x) x.Supplier_Name.Contains(supp))
            End Select
        End If
    Next
    gridData.DataSource = query.ToList()
    Return gridData
End Function

So right now I am trying to see if there is a way for me to modify the code in a way that doesn't essentially involve me putting a substring search into each Case section to determine if I should be using StartsWith() , Contains() , or EndsWith .

Thanks for your time.

如果您正在使用LINQ to SQL,并且正在与Microsoft SQL Server通讯,则可以使用SQLMethods.Like来实现SQL LIKE

query = query.Where(Function(x) SQLMethods.Like(x.Part_Number, partNum))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM