简体   繁体   English

针对实体框架使用 Linq 显示等效于 SQL pivot 表

[英]Displaying equivalent to SQL pivot table using Linq against Entity Framework

I've been struggling for a few days to display something like Pivoting a dynamic table on SQL, using Linq.几天来,我一直在努力使用 Linq 在 SQL 上显示类似 Pivoting a dynamic table 的内容。 I don't actually want to create a pivoted table, I just want to display the results as if it was a pivoted table.我实际上并不想创建一个透视表,我只想显示结果,就好像它是一个透视表一样。

I have two entities:我有两个实体:

Category:类别:

 public int Id { get; set; }
        public string Name { get; set; }
        public string Icon { get; set; }
        public ICollection<StaticEvent> StaticEvents { get; set; }

StaticEvent:静态事件:

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;}

I'm trying to generate a table showing the COUNT of STATIC EVENTS per CATEGORY PER YEARMONTH.我正在尝试生成一个表格,显示每年每个类别的 STATIC 事件的计数。 So the rows would be the YEARMONTH, the columns would be the Categories and the values would be the COUNT.因此,行将是 YEARMONTH,列将是类别,值将是 COUNT。

在此处输入图像描述

I got to the point where I can count the STATIC EVENTS per YEARMONTH:我到了可以计算 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);}

but I'm lost about what to do from here.但我不知道从这里做什么。

If Categories is unknown values which are stored in database, it is not possible to do that via LINQ without dynamic query creation.如果类别是存储在数据库中的未知值,则无法通过 LINQ 执行此操作,而无需创建动态查询。

There is query which do the job when you known categories on the compile time.当您在编译时知道类别时,有一个查询可以完成这项工作。 Since you have not specified EF version, I have emulated Count with Sum :由于您没有指定 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM