Search code examples
joinasp.net-mvc-2fluent-nhibernatehql

Multiple Table Join HQL (ASP.NET MVC 2 with Fluent nHibernate)


I have a web application written in asp.net mvc with fluent nhibernate. I have 4 tables in hierarchy. Which

Vote -> Post -> Category -> Company

I try to build a query which will list all company posts which voted in last 3 days.

Take Votes of Company :

IList<Vote> votes = session.CreateCriteria(typeof(Vote))
                            .CreateAlias("Post", "post")
                            .CreateAlias("Category", "category")
                            .Add(Restrictions.Eq("category.Company", pCompany))
                            .Add(Restrictions.Between("VoteDate", DateTime.Today.AddDays(-3), DateTime.Today))
                            .List<Vote>();

Take Posts of above votes:

IList<Post> companyPosts= votes.Select(v=> v.Post).ToList();

Grouping Posts based on Category :

List<IGrouping<int, Post>> groupbyTopic = 
                          (List<IGrouping<int, Post>>)
                          (from p in companyPosts group p by p.Topic.Id);


CreateCriteria gives error. 
NHibernate.QueryException: could not resolve property: Topic of: App.Models.Vote

Any suggestion and good recommandation for an efficient query which will list all company posts which are voted in last 3 days.


Solution

  • you havent specified the alias => .CreateAlias("post.Category", "category")

    alternativly you can query like this:

    IList<Vote> votes = session.CreateCriteria(typeof(Vote))
                            .Add(Restrictions.Between("VoteDate", DateTime.Today.AddDays(-3), DateTime.Today))
                            .CreateCriteria("Post")
                            .CreateCriteria("Category")
                            .Add(Restrictions.Eq("Company", pCompany))
                            .List<Vote>();