如何在nhibernate中进行子查询?

时间:2011-05-11 19:00:50

标签: nhibernate queryover

我需要在子集合上做一个子查询,但我无法让它工作。

我试过这个

 Task tAlias = null;
        List<Task> result = session.QueryOver<Task>(() => tAlias)
                                   .Where(Restrictions.In(Projections.Property(() => tAlias.Course.Id), courseIds))
                                   .WithSubquery.WhereExists(QueryOver.Of<CompletedTask>().Where(x => x.Student.StudentId == settings.StudentId))                                     
().ToList();

但我得到了

  

无法在条件上使用子查询   没有投射。

1 个答案:

答案 0 :(得分:24)

session.QueryOver<Task>(() => tAlias)
    .WhereRestrictionsOn(x => x.Course.Id).IsIn(courseIds)
    .WithSubquery.WhereExists(QueryOver.Of<CompletedTask>()
        .Where(x => x.id == tAlias.id) //not sure how you need to link Task to CompletedTask
        .Where(x => x.Student.StudentId == settings.StudentId)
        .Select(x => x.id)) //exists requires some kind of projection (i.e. select clause)
    .List<Task>();

或者如果你只想要完成任务那么......

Task taskAlias = null;

session.QueryOver<CompletedTask>()
    .JoinAlias(x => x.Task, () => taskAlias)
    .WhereRestrictionsOn(() => taskAlias.Course.Id).IsIn(courseIds)
    .Where(x => x.Student.StudentId == settings.StudentId)
    .List<CompletedTask>();

或考虑在Task.CompletedTasks集合上设置学生过滤器。我以前从未使用过这个功能。我相信你必须在运行查询之前启用过滤器并设置student参数。那么你的Task对象只包含那个学生的completedTasks ......

http://nhibernate.info/doc/nh/en/index.html#filters