Andreas Eriksson
Andreas Eriksson

Reputation: 548

Fluent NHibernate Where on Empty String

I'm applying a .Where()-restriction on an IQueryOver<T,T> in FluentNH, as such:

.Where(x => x.Col1 == null || x.Col1 == "");

Which generates the following SQL:

WHERE (Col1 IS NULL OR Col1 = NULL)

How can I make NH understand that empty string means empty string?

Upvotes: 1

Views: 1403

Answers (1)

Thiago S&#225;
Thiago S&#225;

Reputation: 852

You can write your Where clause like this:

.Where(Restrictions.On<ClassType>(obj => obj.Col1).IsNull ||
       Restrictions.On<ClassType>(obj => obj.Col1).IsLike(@""))

Alternatively, if you're doing this on several queries you should consider creating a query extension:

public static class QueryExtention {
    public static IQueryOver<E, F> WhereStringIsNullOrEmpty<E, F>(this IQueryOver<E, F> query, Expression<Func<E, object>> expression) {
        var property = Projections.Property(expression);
        var criteria = Restrictions.Or(Restrictions.IsNull(property),
                                       Restrictions.Eq(property, string.Empty));
        return query.Where(criteria);
    }
}

Then you should be able to create something like:

.QueryOver<ClassType>()
.WhereStringIsNullOrEmpty(obj => obj.Col1)

Upvotes: 1

Related Questions