Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - case insensitive Contains?

I want a solution to this problem that does not involve ToUpper or ToLower, as I use in the code below;

var upper = term.ToUpper(); using (var db = this.DataContext) {     return db.Counties.Where(x => x.CountyName.ToUpper().Contains(upper)).ToList(); } 

I am using entitly framework so the C# solution of using StringComparison.CurrentCultureIgnoreCase does not work. It does work for Equals, EndsWith and StartsWith, but not Contains.

like image 638
arame3333 Avatar asked Jan 18 '13 14:01

arame3333


People also ask

Is EF core case sensitive?

For one thing, EF Core does know not which case-sensitive or case-insensitive collation should be used. More importantly, applying a collation would in most cases prevent index usage, significantly impacting performance for a very basic and commonly-used .

How do you check if a column is case sensitive in SQL Server?

SQL Server is, by default case insensitive; however, it is possible to create a case sensitive SQL Server database and even to make specific table columns case sensitive. The way to determine a database or database object is by checking its “COLLATION” property and look for “CI” or “CS” in the result.

What is COLLATION case-insensitive?

A case-insensitive collation ignores the differences between uppercase and lowercase letters for string comparison and sorting, whereas a case-sensitive collation does not. For example, in case-insensitive collation, “A” and “a” are equal.

Is SQL Linq case sensitive?

LINQ has no concept of case sensitivity, it only cares about boolean evaluation. So if you want to ignore case, you should do something like: query = query.


2 Answers

I use EF6 and Sql Server and Contains is mapped to LIKE '%@p0%' which is case insensitive in my case. So in my case:

db.Counties.Where(x => x.CountyName.Contains(term)).ToList(); 

works as needed. More info in Sjoerd answer.

like image 51
Vladislav Kostenko Avatar answered Sep 22 '22 17:09

Vladislav Kostenko


I know that this is not related directly to EF, but only solution I can think of is to alter DB table column collation to be Case Insensitive e.g.:

ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME nvarchar(100) COLLATE Latin1_General_CI_AS NULL 

CI - case insensitive / CS - case sensitive

AS - accent sensitive / AI - accent insensitive (can also be useful)

If you can't change collation of table column you can use direct query from EF with forcing collation

select *  from table where country collate Latin1_General_CI_AS != @country 
like image 22
Tomas Avatar answered Sep 22 '22 17:09

Tomas