Search code examples
nhibernatecoalescequeryover

NHibernate QueryOver order by first non-null value (coalescing)


What I'm trying to come up is something that's expressed like this:

var result = Session.QueryOver<Foo>().OrderBy(f => f.UpdatedAt ?? f.CreatedAt);

Sure enough, this doesn't work. Rough equivalent of this in T-SQL is

... order by coalesce(f.UpdatedAt, f.CreatedAt)

What's the kosher way to do "coalescing" in NHibernate QueryOver?


Solution

  • .OrderBy(Projections.SqlFunction("coalesce",
                                     NHibernateUtil.DateTime,
                                     Projections.Property<Foo>(x => x.UpdatedAt),
                                     Projections.Property<Foo>(x => x.CreatedAt)))