views:

134

answers:

2

Right now I have something like this in NHibernate:

Expression.Like(property, value, MatchMode.Anywhere)

and that generates SQL like:

property LIKE '%value%'

which is fine for that case. In another case, I want the SQL:

IFNULL(property LIKE '%value%', 0)

but I don't see any example in the manual that refers to IFNULL, nor can I even find any plain-ol' API docs.

I found Expression.Sql(), but only the one example in the manual, and it scares me a little both to use something for which I haven't seen any real docs, and to be doing anything with SQL myself when I'm using NHibernate to try to get away from that.

Is there a better way to do IFNULL in NHibernate than Expression.Sql()?

A: 

It isnt a answer per se but i suggest you to look for COALESCE(). Here you can see why.

Leonel Martins
That's neat, and if I ever want to use ISNULL (which I'm not, here), I'll be sure to check it out. :-)
Ken
+2  A: 

I'm assuming this is in a WHERE clause, at which point IFNULL(property LIKE '%value%', 0) is not valid SQL since LIKE evaluates to true or false, and 0 is neither of those.

I suspect you actually want property LIKE '%value%' OR property IS NULL?

If this is the case:

.Add(
    Expression.Disjunction()
    .Add(Expression.Like(property, value, MatchMode.Anywhere))
    .Add(Expression.IsNull(property))
)
KeeperOfTheSoul
I think you meant AND NOT NULL instead of OR NULL, but I was able to use this strategy to make an Expression that works for me.
Ken
If you didn't want nulls why would you even use coalesce anyway? You could just use the LIKE since that would never match a null and thus x LIKE 'value' AND x IS NOT NULL is exactly the same as if you remove the IS NOT NULL.
KeeperOfTheSoul
Because "COALESCE(x LIKE y, false)" looks a lot simpler and more direct to me than "(x LIKE y) AND (x IS NOT NULL)". And simply using "x LIKE y" gives NULL when x=NULL which is completely different -- in particular, when used inside an Expression.Not(), NULL is still NULL.
Ken
Ah good point on the NOT(...)
KeeperOfTheSoul
Would that just be; NOT (x LIKE 'y') AND x IS NOT NULL ? If x is null then the lhs would be null, and the rhs false, null and false == false. Otherwise the lhs would be true or false, and the rhs would be true.
KeeperOfTheSoul