简体   繁体   中英

Filtered join with NHibernate QueryOver

Using the Criteria API, I can generate a query that creates a JOIN with an extra condition on the 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"));

This generates a JOIN similar to this:

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

How do I do the same thing with the QueryOver syntax?

.JoinAlias has an overload with a withClause

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

Off the top of my head I think it's like:

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

Edit: Included OrderBy, and gave it a test. Works.

Using the Blog > Posts type example, the generated SQL looks like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM