NZJames
NZJames

Reputation: 5055

NHibernate Queryable not allowing string comparison

I have the following code

var results =
                repository.GetItemsAsQuery<User>().Where(
                    user => user.EmailAddress.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase));

            return results.Any();

Repository is just my wrapper around the NHibernate session and that method has the following signature

public IQueryable<T> GetItemsAsQuery<T>()
        {
            try
            {
                CheckHasErrored();

                return _connection.Session.Query<T>();
            }
            catch (Exception ex)
            {
                HasErrored = true;
                throw new DataRepositoryException(string.Format("Error getting collection of items of type '{0}'", typeof(T).Name), "DataRepository.GetItems<>", ex);        
            }
        }

When I run the first method, I get the error NotSupportException - Boolean Equals(System.String, System.StringComparison) with source NHibernate.

Which seems to imply the error is coming from the LINQ lambda expression that I am trying to filter the NHibernate query on

user.EmailAddress.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase)

Am I using NHibernate Queryable wrong? The equivalent SQL I want it to generate is

select * from User where emailAddress = @emailAddress

So I only get one row returned across the data network.

Upvotes: 5

Views: 4194

Answers (3)

Keysharpener
Keysharpener

Reputation: 504

LINQ is not yet 100% compatible with Nhibernate. Try using String.Compare(string a, string b) instead.

Upvotes: 1

Jay Pete
Jay Pete

Reputation: 4249

String.Compare is now supported in NHibernate.

Upvotes: 2

Marcelo Zabani
Marcelo Zabani

Reputation: 2279

I see two big problems with your question/what you want:

  • Your desired SQL query is incompatible with your string comparison method. Your string comparison method would return true when comparing "StRiNg" and "string", since it ignores the strings' case, while your SQL query would return false when comparing these strings. If you want to ignore case when comparing, you should change your query to:

repository.GetItemsAsQuery().Where( user => user.EmailAddress.ToLower() == emailAddress.ToLower());

And if I'm not mistaken this is already possible with NHibernate.

  • Your next big problem is trying to make a culture aware comparison in your SQL query. This is not yet possible with NHibernate. If you want culture aware string comparison SQL queries you will have to write these queries in plain SQL. For a simple equality comparison, however, you probably won't have a problem: just use the == operator for string comparison and you will do just fine.

Hope it helps!

Upvotes: 4

Related Questions