Lesser-Known NHibernate Features: Mixing Client and Server-Side Calls in Projections

Another not widely known feature of NHibernate: mixing client and server-side calls.

To illustrate this, imagine that you want to calculate the difference between a mapped DateTime property and the current time, DateTime.Now. The following query works in NHibernate, but not in other O/RM frameworks:

   1: var timespans = session.Query<Order>().Select(x => DateTime.Now - x.Date).ToList();

The generated SQL will only be:

   1: select
   2:     order0_.[date] as col_0_0_
   3: from
   4:     [
   5: order] order0_

But NHibernate will detect that the result needs to be combined with something from the client side and will return a TimeSpan. This mechanism is extensible – more on this in a future post.

In other O/RMs, which shall remain unnamed, you have to use LINQ to Objects after LINQ to Unnamed Framework:

   1: ctx.Orders.Select(x => new { ElapsedTime = SqlFunctions.DateDiff("HOUR", x.Date, DateTime.Now) }).ToList().Select(x => TimeSpan.FromHours(x.EllapsedTime));

Pretty cool, don’t you think? Winking smile

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website