Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a case-insensitive string where in NHibernate Linq query?

How to do a case-insensitive where in NHibernate Linq query?

e.g.

//note this one doesn't work if the entry in database has lowercase
q => q.Where(entity => 
    entity.CaseInsensitiveField == DesiredField.Trim().ToUpper())
like image 747
Louis Rhys Avatar asked Mar 23 '12 03:03

Louis Rhys


People also ask

Is Linq where clause 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

Try this:

q => q.Where(entity => entity.CaseInsensitiveField.ToUpper() == DesiredField.Trim().ToUpper())

Also, I would suggest to set the parameter outside the query:

var value = DesiredField.Trim().ToUpper();

...

q => q.Where(entity => entity.CaseInsensitiveField.ToUpper() == value)
like image 163
Ivo Avatar answered Sep 28 '22 07:09

Ivo


Use this:

q => q.Where(entity => 
    String.Equals(entity.CaseInsensitiveField , CaseInsensitiveField , 
                  StringComparison.OrdinalIgnoreCase));

UPDATE

It appears (at least via LinqPad) that the above will not translate into SQL, so I would suggest, as ivowiblo has already suggested:

var comparisonValue = CaseInsensitiveField.ToUpper();
q => q.Where(entity => 
    entity.CaseInsensitiveField.ToUpper() == comparisonValue);

The reason to set the ToUpper beforehand is that procedural functions are generally worse in SQL, and since this is not a database field, we can send it in already capitalized.

like image 36
Justin Pihony Avatar answered Sep 28 '22 06:09

Justin Pihony