簡體   English   中英

針對實體框架使用 Linq 顯示等效於 SQL pivot 表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM