Search code examples
nhibernatefetcheager-loadingqueryover

Am I doing something wrong with Nhibernate Query Over fetch?


I have this

   using (ITransaction transaction = session.BeginTransaction())
        {
            Task tAlias = null;
            CompletedTask cAlias = null;

            List<Task> tasks = session.QueryOver<Task>(() => tAlias)
                .Where(Restrictions.In(Projections.Property(() => tAlias.Course.Id), courseIds))
                .Fetch(pt => pt.PersonalTaskReminders).Eager
                .List<Task>().ToList().ConvertToLocalTime(student);


            transaction.Commit();

            return tasks;
        }

    PersonalTaskReminders == Collection

So a task can have many personalTaskReminders. I am finding though if I set 2 personalTaskReminders(so PersonalTaskReminders will now have 2 rows in it's collection from the db)

That it returns the same task twice.

So if I had 50 personaltaskReminders for that task. I would get 50 results of the same task. I don't understand why.

If I remove the eager loading. I get the one task back from the database as I expected.


Solution

  • It is obvious, because eager fetch causes join with 2 tables. To get rid of duplicated results you should use DistinctRootEntityTransformer.

    By the way, NHibernate offers much nicer syntax for IN clause. So your query should look like this:

        var tasks = Session.QueryOver<Task>()
                .WhereRestrictionOn(x => x.Id).IsIn(courseIds)
                .Fetch(pt => pt.PersonalTaskReminders).Eager
                .TransformUsing(Transformers.DistinctRootEntity)
                .List<Task>();