开发者

NHIbernate: Setting up subquery to use property value from outer query

开发者 https://www.devze.com 2023-02-25 01:02 出处:网络
I have the following sub/criteria: var sq = DetachedCriteria.For<Title>() .CreateAlias(\"Genres\", \"genre\")

I have the following sub/criteria:

var sq = DetachedCriteria.For<Title>()
  .CreateAlias("Genres", "genre")
  .Add(Restrictions.IsNull("genre.ParentId"))
  .SetProjection(Projections.Property<Genre>(g=>g.Name));

var q =
  session.CreateCriteria(typeof(Title))
      .SetProjection(
            Projections.Alias(Projections.SqlFunction("array", null, Projections.SubQ开发者_运维百科uery(sq)), "TopLevelGenre"),
            Projections.Property<Title>(t1=>t1.Id)
        )
        .SetMaxResults(5);

Which results in the following SQL query:

SELECT array((SELECT this_0_.title as y0_
          FROM   title this_0_
                 inner join title_genre genres3_
                   on this_0_.title_id = genres3_.title_id
                 inner join genre genre1_
                   on genres3_.genre_id = genre1_.genre_id
          WHERE  genre1_.parent_id is null)) as y0_,
   this_.title_id                             as y1_
FROM   title this_
limit  5 /* :p1 */

How do I set it up so that my subquery uses the value of a property from the outer query? For example, I'd like for the subquery to filter by the title_id value. Is there anything in NHibernate that allows me to project a property value to the subquery?

Thanks!


Turns out I was close. All I had to do was create an alias for Title and use that in the Where clause of my subquery.

Title title = null;

c = Session
  .QueryOver(() => title)
  ....
  .SelectList(list => list
      .Select(Projections.Alias(Projections.SqlFunction("array", null, Projections.SubQuery(sq.Where(tt => tt.Id == title.Id))), "TopLevelGenre"))
  );

Hope that helps someone..

0

精彩评论

暂无评论...
验证码 换一张
取 消