Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Thursday 20 October 2011

Generate summary using multiple aggregations with NHibernate

NHibernate allows adding multiple aggregations at the same time for a single ICriteria and generates multiple objects. Below sample shows how this can be achieved

using (var session = _sessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(InvoiceLine));
                criteria.Add(Restrictions.Where(i => i.Invoice.ID == 1234));
                criteria.SetProjection(Projections.ProjectionList()
                    .Add(Projections.Count("ID"))
                    .Add(Projections.Sum("Price"))
                    .Add(Projections.Sum("Quantity"));
                object[] retObjects = (object[])criteria.UniqueResult();    
            }

Now you have got some list of objects which you can convert to your desired type. So you have to manually covert them, how about if NHibernate does this for you. First create a summary class which does not need to be part of you database
public class InvoiceSummary
    {
        public int LineCount;
        public long LineTotalPrice;
        public long TotalQuantity;        
    }
Now populate the data
      using (var session = _sessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(InvoiceLine));
                criteria.Add(Restrictions.Where(i => i.Invoice.ID == 1234));
                criteria.SetProjection(Projections.ProjectionList()
                    .Add(Projections.Count("ID").As("LineCount"))
                    .Add(Projections.Sum("Price").As("LineTotalPrice"))
                    .Add(Projections.Sum("Quantity").As("TotalQuantity")));
     .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(InvoiceSummary)));
                InvoiceSummary summary = (InvoiceSummary)criteria.UniqueResult();
            }
NHibernate.Transform.Transformers.AliasToBean does the job of using the alias names to assign the properties of InvoiceSummary object Technological progress has merely provided us with more efficient means for going backwards. ~Aldous Huxley

0 comments:

Post a Comment

Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers