Monday, February 21, 2011

LIKE in Linq to SQL

I have a method that needs to accept an array of country names, and return a list of records that match one of those country names. I'm trying this

Public Shared Function GetConcessions(ByVal Countries As String()) As IEnumerable
    Dim CountryList As String = Utility.JoinArray(Countries) ' turns string array into comma-separated string
    Return (From t In New Db().Concessions _
                    Where CountryList Like t.Country _
                    Select t.ConcessionID, t.Title, t.Country)
End Function

but I get this error

  *Only arguments that can be evaluated on the client are supported for the LIKE method

In plain SQL, this would be simple:

 Select ConcessionID,Title from Concessions c where @CountryList like '%' + c.Country + '%'

How can I achieve this result in Linq to SQL?

Edit (clarification)

I get the same message with string.Contains. It would be fine with

t.Country.contains(CountryList)

but I need

CountryList.contains(t.Country)

and that throws the same error I listed above.

From stackoverflow
  • You can use SqlMethods.Like

    e.g.

    Where SqlMethods.Like(t.country, "%Sweden%")
    
    ctrlShiftBryan : very nice when u need to put the database field on the right side :)
  • I think what you want to do is construct a List from Countries and use

    List<string> ListOfCountries = new List(Countries)
    
    ...ListOfCountries.Contains(t.Country)
    

    This would translate into

    t.Country IN ('yyy','zzz',...)
    

    Please excuse my C#-ishness..

    leppie : +1 Wow! I was always wonder if LINQ used 'in'. Thanks :)
    Herb Caudill : Perfect - that works. Thanks.

0 comments:

Post a Comment