【发布时间】:2018-07-11 01:25:30
【问题描述】:
我正在工作中构建步数跟踪网络应用。我正在使用最新的 EF Core。我正在与之交互的三个表:
- wg:WellnessGroup(WellnessGroupId,名称)
- wgu:WellnessGroupUser(查表:WellnessGroupId、EmployeeId)
- wsl: WellnessStepsLog (EmployeeId, StepCount)
我想要的是获得所有 WellnessGroups 和该组的总步数。如果该组还没有附加步骤,我希望 NULL 值为 0。我有这个 SQL 语句,它给了我所需的数据:
SELECT wg.Name, SUM(ISNULL(wsl.StepCount, 0)) AS steps
FROM dbo.WellnessGroup AS wg
LEFT JOIN dbo.WellnessGroupUser AS wgu
ON wgu.WellnessGroupId = wg.Id
LEFT JOIN dbo.WellnessStepsLog AS wsl
ON wsl.EmployeeId = wgu.AzureAdUserId
GROUP BY wg.Name
ORDER BY steps DESC;
我已经设法将 2 个 LINQ 表达式一起放在我的控制器上,这只会给我提供与它们相关联的步骤的 WellnessGroup,如果没有步骤,则不会给我 WellnessGroup 数据:
var query = _dbContext.WellnessGroupUser
.Include(x => x.WellnessGroup)
.Join(_dbContext.WellnessStepsLog, group =>
group.AzureAdUserId, steps => steps.EmployeeId,
(group, steps) => new
{
Steps = steps.StepCount,
Date = steps.TrackedDate,
Group = group.WellnessGroup.Name
}).Where(x => x.Date >= yearToDate).Where(x => x.Date <= endDate);
var stepsByGroup = query
.GroupBy(x => x.Group)
.Select(s => new
{
Group = s.Key,
Date = s.Max(x => x.Date),
Steps = s.Sum(x => x.Steps)
});
【问题讨论】:
标签: c# asp.net entity-framework linq entity-framework-core