tags:

views:

496

answers:

1

Hi,

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

+1  A: 

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>();
Darin Dimitrov
Are you sure this works? I bet it does not. It's the joins that won't allow get the row counts right. (I don't know the solution though.)
Rashack
It actually does work. Thanks!
Malcolm
The duplicated rows come from the left join. NHibernate uses the primary key of the Recipe model to filter duplicate rows when DistinctRootEntity transformer is set. Bear in mind though that the filtering is done in-memory after the rows are fetched and not at the database level.
Darin Dimitrov