简体   繁体   English

Fluent Nhibernate - 通过 group by 加入查询

[英]Fluent Nhibernate - Join query with group by

I'm having trouble executing a join query in NHibernate.我在 NHibernate 中执行连接查询时遇到问题。 I have the following tables :我有以下表格:

BOOKS:
ID, NAME, BOOK_TYPE, AUTHOR_ID

AUTHORS:
ID, FIRST_NAME, LAST_NAME, BIRTH_DATE

And I want to execute the following sql query in Fluent NHibernate:我想在 Fluent NHibernate 中执行以下 sql 查询:

SELECT AUTHORS.ID, COUNT(BOOKS.ID)
FROM AUTHORS
INNER JOIN BOOKS
ON AUTHORS.ID = BOOKS.AUTHOR_ID
GROUP BY AUTHORS.ID;

Class:班级:

public class Book
{
     public virtual int id{get; set;}
     public virtual string Name{get; set;}
     public virtual int booktype{get; set;} 
     public virtual Author author{get; set;}
}

public class Author
{
     public virtual int id{get; set;}
     public virtual string FirstName{get; set;}
     public virtual string LastName{get; set;}
     public virtual DateTime BirthDate{get; set;}
     public virtual IList<Book> Books{get; set;}
}

Here is what I have tried:这是我尝试过的:

GraphDTO graph = null;
Session.QueryOver<Book>()
.SelectList(list => list
.SelectGroup(x => x.Author.Id).WithAlias(() => graph.Id)
.SelectCount(x => x.Id).WithAlias(() => graph.BooksNum))
.TransformUsing(Transformers.AliasToBean<GraphDTO>())
.List<GraphDTO>();

Well, we can do it with a join and group by like this好吧,我们可以通过这样的加入和分组来做到这一点

Author author = null;
Book book = null;
var query = session.QueryOver<Contact>(() => author)
    .JoinQueryOver(() => author.Authors, () => book)
    .SelectList(list => list
        .SelectGroup(x => author.ID)
        // we can have more stuff from author table
        .SelectGroup(x => author.LastName)
        .SelectGroup(x => author.FirstName)
        .SelectCount(x => book.ID))
    ;

var result = query.List<object[]>();

But the above SQL in fact would not need JOIN, it could be just as here Fluent Nhibernate - selecting specific column and count query with group by但是上面的SQL实际上不需要JOIN,它可能就像这里的Fluent Nhibernate - 选择特定列并使用group by进行计数查询

session.QueryOver<Book>()
    .SelectList(list => list
        .SelectGroup(c => c.Author.ID)
        .SelectCount(c => c.ID))
    .List<object[]>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM