2011-04-16 69 views
1

使用屬性值我有以下子/標準:NHibernate的:建立子查詢從外部查詢

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.SubQuery(sq)), "TopLevelGenre"), 
      Projections.Property<Title>(t1=>t1.Id) 
     ) 
     .SetMaxResults(5); 

導致下面的SQL查詢:

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 */ 

如何設置以便我的子查詢使用來自外部查詢的屬性的值?例如,我想讓子查詢按title_id值過濾。 NHibernate中有什麼允許我將屬性值投影到子查詢中?

謝謝!

回答

0

原來我很近。我所要做的只是爲Title創建一個別名,並在子查詢的Where子句中使用它。

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

希望幫助別人..