[英]Displaying equivalent to SQL pivot table using Linq against Entity Framework
几天来,我一直在努力使用 Linq 在 SQL 上显示类似 Pivoting a dynamic table 的内容。 我实际上并不想创建一个透视表,我只想显示结果,就好像它是一个透视表一样。
我有两个实体:
类别:
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public ICollection<StaticEvent> StaticEvents { get; set; }
静态事件:
public int Id { get; set; }
public int CategoryId {get; set; }
public Category Category { get; set; }
public DateTimeOffset Time {get; set; }
[MaxLength(500)]
public string Comment {get; set;}
我正在尝试生成一个表格,显示每年每个类别的 STATIC 事件的计数。 因此,行将是 YEARMONTH,列将是类别,值将是 COUNT。
我到了可以计算 STATIC 事件每年的地步:
var query = _context.Categories
.SelectMany(c => c.StaticEvents )
.GroupBy(c =>
new {
Year = c.Time.Year,
Month = c.Time.Month
})
.Select( x=> new {YearMonth = x.Key, Count = x.Count()})
.ToList();
foreach (var x in query)
{Console.WriteLine($"Month = {x.YearMonth.Year},{x.YearMonth.Month}, , Count = " + x.Count);}
但我不知道从这里做什么。
如果类别是存储在数据库中的未知值,则无法通过 LINQ 执行此操作,而无需创建动态查询。
当您在编译时知道类别时,有一个查询可以完成这项工作。 由于您没有指定 EF 版本,因此我使用Sum
模拟Count
:
var query = _context.Categories
.SelectMany(c => c.StaticEvents)
.GroupBy(c =>
new {
Year = c.Time.Year,
Month = c.Time.Month
})
.Select(x => new {
YearMonth = x.Key,
Cat1 = x.Sum(z => z.CategoryId == 1 ? 1 : 0),
Cat2 = x.Sum(z => z.CategoryId == 2 ? 1 : 0),
Cat3 = x.Sum(z => z.CategoryId == 3 ? 1 : 0),
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.