Geeks With Blogs
Łukasz Kuryło's blog

I wrote in current project typical funcion to count the number of elements in db for specific criteria using NHibernate HQL:

 

IQuery query = Session.CreateQuery(@"
               select count(t.ID)
               from Post p
               join p.Tags t
               where t.Name=:tagName and p.Blog.Name=:blogName
               ")
          .SetParameter("tagName", tagName)
          .SetParameter("blogName", blogName);

int result=query.UniqueResult<int>();

 

I was very surpriced to see that I stuck with System.InvalidCastException: Specified cast is not valid.

Solution for this was to change result type to long. What is interesting, with ICriteria this problem doesn't exist:

 

ICriteria criteria = Session.CreateCriteria<Post>()
    .SetProjection(Projections.Count("ID"))
    .CreateAlias("Blog", "b")
    .Add(Restrictions.Eq("b.Name", blogName));

int result = criteria.UniqueResult<int>();

 

NHibernate never ceases to amaze me.

Posted on Tuesday, November 2, 2010 8:52 AM NHibernate | Back to top


Comments on this post: Returning Count(*) with NHibernate HQL

# re: Returning Count(*) with NHibernate HQL
Requesting Gravatar...
Try to use this HQL query :

select cast(count(t.ID) as int)
from Post p
join p.Tags t
where t.Name=:tagName
and p.Blog.Name=:blogName
Left by Ashi4 on Jan 11, 2011 3:33 PM

Comments have been closed on this topic.
Copyright © Łukasz Kuryło | Powered by: GeeksWithBlogs.net