Malcolm
Malcolm

Reputation: 12864

Nhibernate - Loading entity with HasMany collection in web app

Firstly anyone else trying to get onto forum.hibernate.org. I have been trying for a while. Can't believe its down.

I am new to NHibernate. Go easy.

I have an MVC app and I have an entity called Recipe and it has HasMany collections Comments, Ingredients and Images.

In the action of a MVC controller I am loading the first 20 recipes to load on my home page.

I am using the following HQL to do it. I want to prefetch the images so I can display the first one. But my first recipe has 3 images so the query results in 3 rows loaded for the one recipe.

     string sql = "from Recipe r " +
            "left join fetch r.Images " +
            "inner join fetch r.User " + 
            "where r.Completed!=0";
        IList<Recipe> recipes = (IList<Recipe>)session.CreateQuery(sql)
            .SetMaxResults(20)
            .List<Recipe>();

What method do I use to load the first 20 recipes with there images loaded??? I STRESS I want to prefetch images not Lazy load, this is because the list is loaded in the controller action so the images can't be loaded when I enumerate them in my user control.

Malcolm

Upvotes: 2

Views: 880

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Try this:

string sql = "from Recipe r " +
       "left join fetch r.Images " +
       "inner join fetch r.User " + 
       "where r.Completed!=0";

var recipes = session
    .CreateQuery(sql)
    .SetResultTransformer(CriteriaUtil.DistinctRootEntity)
    .SetMaxResults(20)
    .List<Recipe>();

Upvotes: 1

Related Questions