Search code examples
c#nhibernatefluent-nhibernatequeryovernhibernate-criteria

Fluent Nhibernate - selecting specific column and count query with group by


I'm having some trouble excuting a query in fluent nhibernate. I have a table : Books with the following columns:

ID, NAME, YEAR, BOOK_TYPE, AUTHOR_ID

I want to excute the following sql query in Fluent NHibernate:

SELECT BOOK_TYPE, COUNT(*)
FROM BOOKS
GROUP BY BOOK_TYPE

Solution

  • So called Fluent-NHibernate is just a mapping extension. To get data we need NHibernate built n querying features: ICriteria, QueryOver or even a LINQ.

    Based on the documentation we can use projections for the above case, using the QueryOver API

    16.6. QueryOver - Projections

    The code snippet:

    IList selection =
        session.QueryOver<Book>()
            .SelectList(list => list
                .Select(c => c.BooktType)
                .SelectCount(c => c.ID))
            .List<object[]>();