【问题标题】:EntityFramework Core Group By with SumEntityFramework Core Group By 和 Sum
【发布时间】:2020-06-03 02:43:10
【问题描述】:

有一段时间没有编写任何代码了,我正试图通过为我的孩子编写一个小应用程序来跟踪他们在夏天读过的书来摆脱锈迹。 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 查询,但我不知道为什么。任何帮助表示赞赏

【问题讨论】:

  • 在分组之前尝试进行选择。 .Where(m => m.IsActive).Select(m=>new {Name=m.Reader.Name, Pages= m.Book.Pages }) .GroupBy(m => m.Name)...m. Sum(b =>b.Pages)
  • 我已经翻译了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();
  • @Sajid 成功了!谢谢。你能把它作为一个可能的答案,我会把它标记为正确的吗?再次感谢您的帮助
  • @bill 不客气,我很乐意为您提供帮助。答案已添加。

标签: c# linq entity-framework-core


【解决方案1】:

评论中提到,将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();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的建议。我试过了,但我收到一条错误消息“无法将 char 隐式转换为字符串”。这几乎就像第一个被应用于字符串而不是组?
    • 这只是意味着Key是一个char,而viewModel中的“Reader”是一个字符串。你应该能够做到 m.Key.First().ToString()
    猜你喜欢
    • 1970-01-01
    • 2012-09-20
    • 2020-01-19
    • 1970-01-01
    • 2021-01-30
    • 2021-05-09
    • 2016-06-21
    • 2012-09-18
    • 1970-01-01
    相关资源
    最近更新 更多