Louis Rhys
Louis Rhys

Reputation: 35627

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())

Upvotes: 16

Views: 11532

Answers (2)

Justin Pihony
Justin Pihony

Reputation: 67085

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.

Upvotes: 5

Ivo
Ivo

Reputation: 8352

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)

Upvotes: 15

Related Questions