我在NHibernate中执行连接查询时遇到问题。 我有以下表格:
BOOKS:
ID, NAME, BOOK_TYPE, AUTHOR_ID
AUTHORS:
ID, FIRST_NAME, LAST_NAME, BIRTH_DATE
我想在Fluent NHibernate中执行以下sql查询:
SELECT AUTHORS.ID, COUNT(BOOKS.ID)
FROM AUTHORS
INNER JOIN BOOKS
ON AUTHORS.ID = BOOKS.AUTHOR_ID
GROUP BY AUTHORS.ID;
类别:
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;}
}
以下是我的尝试:
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>();
答案 0 :(得分:2)
好吧,我们可以通过加入和分组来实现这个
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[]>();
但是上面的SQL实际上不需要JOIN,它可能就像这里Placing Dates in Your Titles
session.QueryOver<Book>()
.SelectList(list => list
.SelectGroup(c => c.Author.ID)
.SelectCount(c => c.ID))
.List<object[]>();