0

I have read Case insensitive Contains(string), Why would Entity Framework not be able to use ToString() in a LINQ statement? and many other questions but I still can't figure out the right way.

string searchString = "max";
private db = new DbContext();

IQueryable<Person> persons = from m in db.Persons
                          select m;
if (null != persons)
{
     //do what it should but marked as codesmell because of .ToStrong() with no culture
     persons = persons.Where(s =>
        s.person_name.ToLower().Contains(searchString.ToLower())); 

     //NotSupportedException
     persons = persons.Where(s =>
        cultureInfo.CompareInfo.IndexOf(s.person_name, searchString, CompareOptions.IgnoreCase) >= 0); 

     //NotSupportedException
     persons = persons.Where(s =>
        s.person_name.ToLower(CultureInfo.InvariantCulture).Contains(searchString.ToLower(CultureInfo.InvariantCulture)));  
}

What is the right way to do a case insensitive string search in a db with LINQ?

Community
  • 1
  • 1
Paul S
  • 89
  • 12
  • this thing is related to database level that what collation is defined on the database – Ehsan Sajjad Mar 10 '17 at 15:27
  • The LINQ expression has to be converted to SQL. Not every LINQ expression has an equivalent in SQL. – chadnt Mar 10 '17 at 15:28
  • Take a look at [This SO post](http://stackoverflow.com/questions/13577981/is-it-possible-to-include-sqlfunctions-stringconvert-in-a-lambda-expression). I have done similar things. – Craig Selbert Mar 10 '17 at 15:34
  • *marked as codesmell* is indeed the only LINQ to Entities supported (hence the right) way. So just use it and move on. – Ivan Stoev Mar 10 '17 at 19:53

0 Answers0