使用NHibernate QueryOver过滤连接

时间:2011-11-22 07:44:40

标签: nhibernate join queryover

使用Criteria API,我可以生成一个查询,在JOIN上创建一个带有额外条件的JOIN

var criteria = Session.CreateCriteria<Product>()
   .SetReadOnly(true)
   .SetMaxResults(1)
   .CreateAlias("ProductCategory", "U", JoinType.LeftOuterJoin, Expression.Eq("U.SubType", "Premium"))
   .AddOrder(Order.Desc("U.Sequence"));

这会产生类似于此的JOIN:

SELECT * FROM dbo.Product w
LEFT JOIN dbo.ProductCategory u
ON u.DefaultProductId = w.Id AND u.SubType = 'Premium'

如何使用QueryOver语法执行相同的操作?

2 个答案:

答案 0 :(得分:0)

我认为这就像是:

ProductCategory category = null;

var result = Session.QueryOver<Product>()
                    .JoinAlias(x => x.Categories, () => category, JoinType.LeftOuterJoin)
                    .Where(() => category.SubType == "Premium")
                    .OrderBy(() => category.Sequence).Desc
                    .Take(1)
                    .List();

编辑:包含OrderBy,并给它一个测试。的工作原理。

使用博客&gt;帖子类型示例,生成的SQL如下所示:

SELECT this_.Id           as Id1_1_,
       this_.Title        as Title1_1_,
       post1_.BlogId      as BlogId3_,
       post1_.Id          as Id3_,
       post1_.Id          as Id3_0_,
       post1_.Title       as Title3_0_,
       post1_.Content     as Content3_0_,
       post1_.DatePosted  as DatePosted3_0_,
       post1_.BlogId      as BlogId3_0_
FROM   [Blog] this_
       left outer join [Post] post1_
         on this_.Id = post1_.BlogId
WHERE  post1_.DatePosted > '2011-11-22T19:43:11.00' /* @p0 */
ORDER  BY post1_.DatePosted desc

答案 1 :(得分:0)

.JoinAlias有一个带有 withClause

的重载
var result = Session.QueryOver<Product>()
    .Left.JoinAlias(x => x.Categories, () => category, c => c.SubType == "Premium")
    .OrderBy(() => category.Sequence).Desc
    .Take(1)
    .List();