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())
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With