NHibernate:Group by和Count

时间:2009-03-28 15:40:58

标签: nhibernate

我有一个User,Book和UserBooks关联表。像这样的UserBooks表

|UserID | BookID  | Status    |
   1        34      Read
   1        35      Unread 
   2        34      Read
   2        70      Read
   2        32      Unread  
   ...................

我的域类是用户预订 UserBook 。在NHibernate中,我怎样才能获得前10本最多的阅读书籍以及用户的阅读量?

十大阅读书籍

| BookID | ReadCount |
   34         2
   70         1
   ...............

1 个答案:

答案 0 :(得分:11)

假设您使用composite-element映射UserBook类:

var top10Books = session
    .CreateQuery(@"select b.Book 
                   from User u 
                   join fetch u.Books b 
                   where b.Status = :status")
    .SetParameter("status", "Read")
    .SetMaxResults(10)
    .SetResultTransformer(CriteriaSpecification.DistinctRootEntity)
    .List<Book>();

这是完整源代码的link

编辑:

我发现你需要阅读一本书的次数。这是查询:

var top = session
    .CreateQuery(@"select b.Book, count(b.Book.Id) 
                   from User u join fetch u.Books b 
                   where b.Status = :status 
                   group by b.Book")
    .SetParameter("status", "Read")
    .SetMaxResults(10)
    .List<object[]>();

    foreach (var item in top)
    {
        var book = (Book)item[0];
        var readCount = (long)item[1];
        Console.WriteLine("book id: {0}, read count: {1}", book.Id, readCount);
    }