sqlnhibernatelinq-to-nhibernate

Linq to NHibernate: Select multiple sums at once


Is there a way to select multiple sums at once using Linq to NHibernate?

Now I have

int? wordCount = (from translation in session.Query<TmTranslation>()
                  where translation.SatisfiesCondition
                  select translation.TranslationUnit)
                 .Sum(x => (int?)(x.WordCount + x.NumberCount)) ?? 0;

int? tagCount = (from translation in session.Query<TmTranslation>()
                 where translation.SatisfiesCondition
                 select translation.TranslationUnit)
                .Sum(x => (int?)(x.TagCount)) ?? 0;

int? characterCount = (from translation in session.Query<TmTranslation>()
                       where translation.SatisfiesCondition
                       select translation.TranslationUnit)
                      .Sum(x => (int?)(x.CharacterCount)) ?? 0;

which generates three different SQL queries. In SQL I can grab them all three at once, but is there a way to do this in Linq to NHibernate?

Thank you.


Solution

  • Having multiple aggregate functions within a Select() call works and results in a single SQL command sent to the database. For example:

    var result = session.Query<TmAssignment>()
                        .Select(a => new
                        {
                           Words = session.Query<TmTranslation>().Where(s => s.Assignment == a).Sum(u => (int?) u.WordCount) ?? 0,
                           Others = session.Query<TmTranslation>().Where(s => s.Assignment == a).Sum(u => (int?)(u.TagCount + u.NumberCount)) ?? 0,
                        }).ToList();