簡體   English   中英

如何讓EF查詢返回MVC 5 ASP.NET中多對多關系表的聚合值

[英]How to make EF query who return aggregated values for many to many relation tables in MVC 5 ASP.NET

我有這個 ADO.NET 模型:

數據模型

我在視圖中使用 MVC 有 [post] 表單來請求其中一份報告。 在接收“FormCollection”-數據的控制器操作中,我想查詢誰返回給我此報告中包含的每個標簽及其值。

這是一個想要回報的例子:

Report: A - this is name of report;
{ 

     [0]
       {
          TagName: TAG1
          Value: 0.56 - this value is aggregated value of all values for this tag1
       }
     [1]
       {
          TagName: TAG2
          Value: 2.45 -> this value is aggregated value of all values for this tag2 
       }
}

我試圖這樣做,但沒有奏效:

 var report = db.Reports
                    .Where(r => r.ID == reportID)
                    .Select(r => new {
                        r.Name,
                        r.Tags
                    })
                    .ToList();

如何獲取此結構中標簽的相關值並聚合它們?

如果我理解你是正確的,你想最終得到這個結構:

public class TagWithValue
{
   public string Name { get; set; }
   public double ValueAggrigated { get; set; }
}

public class RemortTags
{
   public string Name { get; set; }
   public IEnumerable<TagWithValue> Tags { get; set; }
}

你可以像這樣填充這個結構:

var report = db.Reports
                .Where(r => r.ID == reportID)
                .Select(r => new RemortTags {
                    Name = r.Name,
                    Tags = r.Tags.Select(x => new TagWithValue {
                               Name = x.Name,
                               ValueAggrigated = x.Sum(y => y.Value1) //that's where you should aggrigate your values. You can use different function if you want
                           })
                })
                .ToList();

解決辦法是:

            var report = db.Reports.FirstOrDefault(r => r.ID == reportID);
        var Tags = report.Tags
            .Select(t => new
            {
                TagName = t.Name,
                Values = t.Values
                        .Where(a => a.TimeStamp > startDate && a.TimeStamp <= endDate)
            }).Select(a => new {
                Name = a.TagName,
                Value = a.Values.Sum(s => s.Value1) })
            .ToList();

結果:

在此處輸入圖片說明

感謝大家的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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