EntityFramework核心分组依据(总和)

时间:2020-05-30 18:34:57

标签: c# linq entity-framework-core

有一段时间没有编写任何代码了,我正试图通过为孩子们编写一个小应用程序来追踪他们整个夏天读过的书来摆脱困境。该数据库很简单,只有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查询,但我不知道为什么。感谢您的帮助

2 个答案:

答案 0 :(得分:0)

好像您在import pygame import random import time pygame.init() window = pygame.display.set_mode((800,600)) class Circle(): def __init__(self, color, x, y, radius, width): self.color = color self.x = x self.y = y self.radius = radius self.width = width def draw(self, win, outline=None): pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width) circles = [] clock = pygame.time.Clock() FPS = 60 current_time = 0 next_circle_time = 0 run=True while run: delta_ms = clock.tick() current_time += delta_ms if current_time > next_circle_time: next_circle_time = current_time + 1000 # 1000 milliseconds (1 second) r = 20 new_circle = Circle((255, 255, 255), random.randint(r, width-r), random.randint(r, height-r), r, r) circles.append(new_circle) window.fill((0, 0, 0)) for c in circles: c.draw(window) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run=False pygame.quit() quit() 中有m.Key。使用select时,select中未在group by中定义的所有值都必须在集合函数中。

尝试将GroupBy更改为m.Key

答案 1 :(得分:0)

如评论中所述,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();