我对 Nhibernate Query Over fetch 做错了吗? [英] Am I doing something wrong with Nhibernate Query Over fetch?

查看:26
本文介绍了我对 Nhibernate Query Over fetch 做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个

   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

所以一个任务可以有很多个人任务提醒.我发现如果我设置了 2 个personalTask​​Reminders(所以 PersonalTask​​Reminders 现在将在它的数据库集合中有 2 行)

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.

因此,如果我有 50 个用于该任务的个人任务提醒.我会得到 50 个相同任务的结果.我不明白为什么.

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.

推荐答案

很明显,因为 eager fetch 导致 join 有 2 个表.要消除重复的结果,您应该使用 DistinctRootEntityTransformer.

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

顺便说一句,NHibernate 为 IN 子句提供了更好的语法.所以你的查询应该是这样的:

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>();

这篇关于我对 Nhibernate Query Over fetch 做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆