Selecting on Sub Queries in NHibernate with Critieria API

前端 未结 1 1209
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 07:45

So I have a SQL query with the following structure:

select p.* from
(
    select max([price]) as Max_Price,
    [childId] as childNodeId
    from [Items] gro         


        
相关标签:
1条回答
  • 2020-12-06 08:23

    I've managed to resolve a similar problem by slightly adapting the original sql query. I've ended up with something like this (pseudo sql code):

    SELECT p.* FROM [Items] as p
    WHERE EXISTS
    (
        SELECT [childId] as childNodeId FROM [Items] as q
        WHERE p.[childId] = q.[childNodeId]
        GROUP BY q.[childId] 
        HAVING p.[price] = MAX(q.[price])
    )
    

    And this is the QueryOver implementation:

    var subquery = QueryOver.Of(() => q)
      .SelectList(list => list.SelectGroup(() => q.ChildId))
          .Where(Restrictions.EqProperty(
              Projections.Property(() => p.Price), 
              Projections.Max(() => q.Price)))
          .And(Restrictions.EqProperty(
              Projections.Property(() => p.ChildId), 
              Projections.Property(() => q.ChildId)));
    

    From here you only need to pass the aliases so that NHibernate can resolve entities correctly (pseudo code):

    var filter = QueryOver.Of(() => p)
        .WithSubquery.WhereExists(GetSubQuery(p, criteria...));
    

    I hope this helps in your particular case.

    UPDATE: Criteria API

    var subquery = DetachedCriteria.For<Items>("q")
        .SetProjection(Projections.ProjectionList()
            .Add(Projections.GroupProperty("q.ChildId")))
        .Add(Restrictions.EqProperty("p.Price", Projections.Max("q.Price")))
        .Add(Restrictions.EqProperty("p.ChildId", "q.ChildId"));
    
    var query = DetachedCriteria.For<Items>("p")
        .Add(Subqueries.Exists(subquery));
    

    Nevertheless I would recommend sticking to the QueryOver version, it's much more intuitive and you avoid magic strings (especially that you don't have to upgrade the NH version).

    Please let me know if this is working for you.

    0 讨论(0)
提交回复
热议问题