繁体   English   中英

EntityFramework Core Group By 和 Sum

[英]EntityFramework Core Group By with Sum

有一段时间没有写任何代码了,我正试图通过为我的孩子编写一个小应用程序来跟踪他们在夏天读过的书来摆脱 rust。 DB很简单,只有3个表。 1 表示书籍(标题、作者、页面等),1 表示读者姓名,1 是实际阅读日志(他们阅读的每本书 1 行,外键与书表和读者表的关系)。

尝试使用 EntityFramework 核心编写一个查询,该查询将返回阅读器读取的总页数。 我可以在 SSMS 中运行它并且效果很好

select r.Name, sum(b.Pages) as PagesRead
from ReadingLog rl
inner join Readers r on rl.ReaderId = r.Id
inner join Books b on rl.BookId = b.Id
where rl.IsActive = 1
group by r.Name

我试着在 EF 中这样写:

var pagesByReader = _context.ReadingLog
                            .Where(m => m.IsActive)
                            .GroupBy(m => m.Reader.Name)
                            .Select(m => new GraphViewModel()
                                   {
                                      Reader = m.Key,
                                      PagesRead = m.Sum(b => b.Book.Pages)
                                   })
                            .ToList();

但我在运行时收到此错误:).Book.Pages' 无法翻译。 以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估

我想我只是写错了 EF 查询,但我不知道为什么。 任何帮助表示赞赏

看起来您在m.Key中有select 使用GroupBy时,select 中未在 group by 中定义的所有值必须在聚合 function 中。

尝试将m.Key更改为m.Key.First()

正如评论中提到的,sql 被翻译成 Linq,就像下面的代码:

var result = (from rl in _context.ReadingLog 
            join r in _context.Readers on rl.ReaderId equals r.Id 
            join b in _context.Books on rl.BookId equals b.Id 
            where rl.IsActive 
            group new {r,b} by r.Name int g 
            select 
            new GraphViewModel 
            { 
                Reader = g.Key, 
                PagesRead = g.Sum(x => x.b.Pages) 
            }).ToList();

暂无
暂无

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

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