这可以从不同的城市组织汽车状态吗?我想使用LINQ(使用查询或方法语法)计算同一车名的汽车总数。我的表名“Cars”如下图所示: 我想我已经有问题如何创建viewmodel并获得部门名称....然后制定LINQ代码...
尝试这样做但是错误的结果: 我想尝试做以下但是给我错误的结果
public class Car
{
public int Id { get; set; }
public string CarName { get; set; }
public int DeptId { get; set; }
public int Status { get; set; }
}
public class Department
{
public int DeptId { get; set; }
public string DeptName { get; set; }
}
public class CarViewModel
{
public string CarName { get; set; } ??? // Is this right?
public Department DeptName { get; set; }
public int Status { get; set; }
}
[HttpGet]
public async Task<ActionResult> GetTotalCars()
{
using (context)
{
var summary = (from c in context.Cars
group c by new { c.CarName, c.DeptId } into grp
join d in context.Departments on grp.Key.DeptId equals d.Id
select new CarViewModel { CarName = grp.Key.CarName,
DeptName = d.DeptName,
Status = grp.Sum(s => s.Status) })
.ToListAsync();
return await summary;
}
}
如果你们帮助我,我将不胜感激。
答案 0 :(得分:1)
以下是您可以按照视图模型提示的方式获取每个车名和每个部门的总计数:
var summary = (from c in Cars
group c by new { c.CarName, c.DeptId } into grp
join d in Departments on grp.Key.DeptId equals d.Id
select new CarViewModel { CarName = grp.Key.CarName,
DeptName = d.DeptName,
Status = grp.Sum(s => s.Status) })
.ToList();