Wednesday, May 13, 2009

Making Linq to Entities do a case-insensitive string comparison.

Linq to Entities by default is case-sensitive for string comparisons. Even for SQL Server, which is case insensitive string comparisons are case-sensitive.

Below are two examples. The first example shows a case-insensitive example, and the second one, shows a case-sensitive example.

// This is NOT case-sensitive
using (MyModel ctx = new MyModel())
{
Reviewer reviewer = ctx.Reviewer.First<Reviewer>(r => r.FirstName.Equals("Brent", StringComparison.CurrentCultureIgnoreCase));
}

// This IS case-sensitive
using (MyModel ctx = new MyModel())
{
Reviewer reviewer = ctx.Reviewer.First<Reviewer>(r => r.FirstName == "Brent");
}

BTW, don’t use the .toLower() method as this translates into a similar call in SQL which then will usually cause your indexes to not be used.

5 comments:

Anonymous said...

Nice

Anonymous said...

If this doesn't work for you it probably because it is not null safe

ctx.Reviewer.First(r =>
r.FirstName != null && r.FirstName.Equals("Brent", StringComparison.CurrentCultureIgnoreCase));

Brent V said...

Anonymous,

Good point about the null check. It was not an issue for me since that field was not nullable and would never be null.

Thanks,

Brent

Carl Partridge said...

...or, if you would like a null value returned if the record cannot be found, simply replace First<> with FirstOrDefault<> eg

ctx.Reviewer.FirstOrDefault(r => ....

Anonymous said...

"Even for SQL Server, which is case insensitive string comparisons..."

This is not true. Case sensitivity depends on the collation of the table. I have the problem of an case insensitive table which I SOMETIMES want to filter case sensitive. No problem in SQL ( ... LIKE '%xxxxxxx%' COLLATE Latin1_General_BIN). No idea how to do it with Linq / Entity Framework.