且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NHibernate QueryOver子查询

更新时间:2022-11-27 13:36:29

嗯,对此进行了更多的散列,尽管我不喜欢其中一部分结果,但它确实有效:

Well, hashed at this some more, and while I don't like one part of the results, it does work:

var distinctProgIdsSubQuery = QueryOver.Of<Program>().
JoinQueryOver<Topic>(p => p.Topics).
WhereRestrictionOn(pt => pt.Id).IsIn(topicIds)
.Select(Projections.Distinct(Projections.Property<Program>(p => p.Id)));


ProgramDTO pDTO = null;
var progQuery = Session.QueryOver<Program>()
    .WithSubquery.WhereProperty(p => p.Id).In(distinctProgIdsSubQuery)
    .SelectList(list => list
        .Select(program => program.Id).WithAlias(() => pDTO.Id)
        .Select(...)
        )
    .TransformUsing(Transformers.AliasToBean(typeof(ProgramDTO)));


return progQuery.List<ProgramDTO>();

这会产生

SELECT this_.ProgramId as y0_, ...
FROM Programs this_ 
WHERE this_.ProgramId in (
        SELECT distinct this_0_.ProgramId as y0_ 
        FROM
            Programs this_0_ 
        inner join
            Programs_Topics topics3_ 
                on this_0_.ProgramId=topics3_.ProgramId 
        inner join
            Topics topic1_ 
                on topics3_.TopicId=topic1_.TopicId 
        WHERE
            topic1_.TopicId in (
                @p1, @p2, ...
            )
    ) 

这可能是NH的局限性,但是不需要需要来连接子查询中的 Programs 表.我试图从另一个方向写这个-即创建一个QueryOver.Of<Topic>(),但是我不知道如何最后选择程序ID-select仅给了我TopicId,即使这样,查询仍在联接所有三个表.

This may be a limitation of NH, but there's no need to join the Programs table in the subquery. I tried to write this from the other direction -- that is, to create a QueryOver.Of<Topic>(), but I could not figure out how to select the program IDs at the end -- select was only giving me the TopicIds, and even then the query was still joining all three tables.

我不确定MS-SQL的查询优化器是否会避免无用的连接,但是如果我们不必依赖它,那就很好了.

I'm not sure if MS-SQL's query optimizer will avoid the useless join or not, but it would be nice if we didn't have to rely on it.

目前,这种方法行之有效,希望其他人比我尝试解决这个问题的头痛要少.

For now though, this works, and hopefully someone else has fewer headaches than I did trying to figure this out.