sqlnhibernateicriteria

How to write the following SQL query in NHibernate


Hey - I'm battling to figure out how to write the following using NHibernate ICriteria (Multi criteria?) for the following:

(It's a query to get a list of first names ordered by popularity in the table in the last day)

select firstname,count(firstname) as occurances from registrants
where timestamp between DateAdd(day,-1, GetDate()) and getdate()
group by firstname
order by count(firstname) desc 

Also, given this is just a couple of columns from a table, excluding the ID, and NHibernate needs ID's for it's objects, what's the easiest way to "fake" an ID so I can just get the results?


Solution

  • You need to use projections and a transformer to do this. Here's some background info http://nhibernate.info/doc/nh/en/index.html#querycriteria-projection

    var criteria = Session.CreateCriteria<Registrant>()
       .Add(Restrictions.Between("Timestamp", DateTime.Now.AddDays(-1), DateTime.Now)
       .AddOrder(Order.Desc(Projections.Count("FirstName")))
       .SetProjection(Projections.ProjectionList()
            .Add(Projections.GroupProperty("FirstName"), "FirstName")
            .Add(Projections.Count("FirstName"), "Occurances")
       .SetResultTransformer(Transformers.AliasToBean<FirstNameOccurance>());
    
    criteria.List<FirstNameOccurance>();
    

    You'll need to create a class called FirstNameOccurance that has 2 properties called FirstName and Occurances.