Linq NHibernate:一次选择多个总和

问题描述:

有没有办法使用Linq到NHibernate一次选择多个总和?Linq NHibernate:一次选择多个总和

现在我有

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; 

产生三种不同的SQL查询。在SQL中,我可以一次抓住所有三个,但有没有办法在Linq中对NHibernate做这件事?

谢谢。

+0

见http://stackoverflow.com/questions/154680/linq-query-with-multiple-aggregates –

+0

你想在一个查询3个款项,或在一次旅行发送到服务器的所有3个查询?无论哪种方式都可以使用QueryOver。 – dotjoe

+0

@dotjoe这将是伟大的,你有一些例子如何做到这一点?我使用QueryOver写了一些查询,但是当我需要更复杂的东西时,我通常会发现它非常复杂,官方文档也没有多大帮助。 – twoflower

已经发送到数据库的Select()通话内容和成果在一个单一的SQL命令中的多个集合函数。例如:

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(); 
+2

很高兴看到您的解决方案 – adriaanp

+0

Soooo ...你的答案是什么?我从来没有低调过,但这不是一个有用的答案。 – mcfea

+0

@mcfea你说得对。我扩大了我的答案。 – twoflower

这应该帮助您开始使用QueryOver方式...

ResultDTO dtoAlias = null; //placeholder alias variable 

var dto = session.OueryOver<TmTranslation>() 
    .Where(x => x.SatisfiesCondition) 
    //Change this to the actual type of Translation property 
    .JoinQueryOver<Translation>(x => x.Translation) 
    .SelectList(list => list 
     //we can sum these columns individually to keep query simple,...add them together later 
     .SelectSum(x => x.WordCount).WithAlias(() => dtoAlias.WordCountTotal) 
     .SelectSum(x => x.NumberCount).WithAlias(() => dtoAlias.NumberCountTotal) 
     //add more select sums to the select list 
     ) 
    .TransformUsing(Transformers.AliasToBean<ResultDTO>()) 
    .SingleOrDefault<ResultDTO>();