c# - 如何使 EF 查询返回 MVC 5 ASP.NET 中多对多关系表的聚合值

标签 c# asp.net asp.net-mvc entity-framework linq

我有这个 ADO.NET 模型:

data-model

我在 View 中使用 MVC 以 [post] 形式请求其中一份报告。 在接收“FormCollection”的 Controller 操作中 - 我想查询谁返回给我此报告中包含的每个标签及其值的数据。

这是一个想要返回的例子:

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();

关于c# - 如何使 EF 查询返回 MVC 5 ASP.NET 中多对多关系表的聚合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415093/

相关文章:

c# - asp.net core 2.0区分过期session和新用户

c# - 排序列表<List<string>>

c# - 捕获委托(delegate)的所有返回值

c# - 如何将一个字符串数组存储到另一个字符串数组中?

asp.net - 使用 OpenID 和 DotNetOpenID 在 ASP.NET 站点中对管理员进行身份验证的安全方法

c# - 使用 ASP.NET MVC 异步 Controller 方法处理多个用户请求

c# - 在 ASP.NET MVC 中使用表单例份验证的自定义 IPrincipal

php - 不同网站中的 IIS 子文件夹

c# - 如果在 asp.net 向导中验证失败则取消步骤

asp.net-mvc - MVC3 Razor 和 Javascript - 大量绿色语法错误