NHibernate QueryOver Subquery

前端 未结 2 1007
滥情空心
滥情空心 2021-01-04 18:08

I\'ve looked at the similar questions, but can\'t find a simple explanation. I could have missed it, but I promise I looked. Actually I can\'t even find the documentation ot

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 18:59

    You need to create a dettached query containing the Id's and then use this sub query with the main query.

    I have pasted an example here so you will need to replace the relevant bits with your class names etc.

    First the set up (you can ignore this bit):-

    public class TestDto {
      public long Id { get; set; }
      public string Name { get; set; }
    }
    ...
    TestDto dto = null;
    var ids = new List { 1,2,5,7 };
    

    Now the dettached query:-

    var idSubQuery = QueryOver.Of()
      .WhereRestrictionOn(w => w.Id).IsIn(ids)
      .Select(Projections.Distinct(Projections.Property(s => s.Id)));
    

    And the final bit is to put it all together:-

    var query = Session.QueryOver()
        .JoinQueryOver(l => l.CmsRegionContentList)
        .WithSubquery
        .WhereProperty(m => m.Id)
        .In(idSubQuery)
        .SelectList(list => list
                                .Select(p => p.Id).WithAlias(() => dto.Id)
                                .Select(p => p.PageName).WithAlias(() => dto.Name)
                    )
                    .TransformUsing(Transformers.AliasToBean(typeof(TestDto)));
    
    var model = query.List();
    

    This will create the following SQL:-

    SELECT
         this_.Id as y0_,
         this_.PageName as y1_ 
    FROM cmspage this_ inner join cmsregioncontent cmsregionc1_ 
      on this_.Id=cmsregionc1_.PageId 
    WHERE cmsregionc1_.Id in (
        SELECT
             distinct this_0_.Id as y0_ 
        FROM cmsregioncontent this_0_ 
        WHERE this_0_.Id in (
            1 /* ?p0 */,
             2 /* ?p1 */,
             5 /* ?p2 */,
             7 /* ?p3 */)
        )
    

    Hopefully you will be able to follow this with your class/property names.

提交回复
热议问题