NHibernate在一对多关系中保持连接选择计数

时间:2011-01-28 17:39:49

标签: nhibernate join count

我在寻找一个正确的合成器后一周没有成功。

我有2个班级:

public class ArtworkData
{
      public virtual Guid Id { get; set; }
      public virtual string Name { get; set; }    
      public virtual IList<CommentData> Comments { get; set; }
}
public class CommentData
{
      public virtual Guid Id { get; set; }
      public virtual string Text { get; set; }
      public virtual ProfileData Profile { get; set; }
      public virtual ArtworkData Artwork { get; set; }
      public virtual DateTime Created { get; set; }
}

我想做这个查询:

    SELECT   this_.ArtworkId          as ArtworkId3_3_,
         this_.Name               as Name3_3_,
         this_.Description        as Descript3_3_3_,
    FROM     Artwork this_
         LEFT outer JOIN 
   (SELECT c.ArtworkIdFk, count(1) Cnt
   FROM Comment c
   GROUP BY c.ArtworkIdFk) as com
   on com.ArtworkIdFk = this_.ArtworkId
    ORDER BY 1 desc

但我找不到路。 此刻我只是有这样的事情:

ICriteria c = this.Session.CreateCriteria(typeof(ArtworkData));
if(filter.Category !=null)
{
      c.CreateAlias("Categories", "cat")
       .Add(Restrictions.Eq("cat.Id", filter.Category.Id));
}
DetachedCriteria crit = DetachedCriteria.For(typeof(CommentData), "comment")
                    .SetProjection(Projections.ProjectionList()
                    .Add(Projections.Count("comment.Id").As("cnt"))    
                .Add(Projections.GroupProperty("comment.Artwork.Id")));                    



c.Add(Expression.Gt(Projections.SubQuery(crit), 0));
   c.AddOrder(Order.Desc(Projections.SubQuery(crit)));

但这不是我想要的。 我希望通过评论数量获得所有艺术品订单(但我不需要获得此编号)。 请帮我!我疯了!

3 个答案:

答案 0 :(得分:1)

我不明白你想用这个奇怪的SQL做什么,但是如果你需要让所有艺术作品有多少评论你可以尝试这个查询:

<query name="ArtworkWithCommentsCount">
   SELECT artwork.Name, artwork.Comments.size
   FROM Artwork artwork
</query>

答案 1 :(得分:1)

如果你使用NHibernate 3,你可以使用这段代码:

var artworks = Session.Query<Artwork>().OrderBy(a => Comments.Count);

或者您可以使用HQL:

Session.CreateQuery("from Artwork a order by size(a.Comments)")

答案 2 :(得分:1)

尝试分离标准。看一下这个blogpost