Entity Framework LINQ contains not case insensitive Entity Framework LINQ contains not case insensitive sql-server sql-server

Entity Framework LINQ contains not case insensitive


It's never been case sensitive for me, but I guess that is just how I set my database up. You can definitely use your first option of converting them both to upper case, EF doesn't pull them into memory to do that, just informs SQL server to do it. For example:

string searchTerm = "Some Text";dbcontext.Table.Where (t => t.Column.ToLower().Contains(searchTerm.ToLower()));

Produces the following SQL (ish, i did this with linqtosql but EF should be pretty similar):

-- Region ParametersDECLARE @p0 NVarChar(1000) = '%some text%'-- EndRegionSELECT *FROM [Table] AS [t0]WHERE LOWER([t0].[Column]) LIKE @p0


From the comments, it sounds like the OP is casting the IQueryable list to an ICollection first, meaning that any subsequent LINQ is running "locally" rather than having the chance to be converted to SQL.

For example,

    // Should be IQueryable<T>    ICollection<User> users = context.Users;    // This is executed in code rather than SQL, and so is case SENSITIVE    users = users.Where(c => c.Name.Contains(searchTerm));

This may have helped debug the issue: How do I view the SQL generated by the entity framework?


Use string.Equals

collection.Where(c => string.Equals(c.Name, searchTerm, StringComparison.CurrentCultureIgnoreCase));

Also, you don't have to worry about null and get back only the information you want.

Use StringComparision.CurrentCulture for Case Sensitive.

collection.Where(c => string.Equals(c.Name, searchTerm, StringComparison.CurrentCulture));