【问题标题】:LINQ EF Grouping and Include exceptionLINQ EF 分组和包含异常
【发布时间】:2016-03-28 10:47:17
【问题描述】:

在创建 LINQ 查询以对相关实体进行分组和过滤时需要帮助。

这是我的模型类。

public class Application
    {
        [DisplayName("Application")]
        public int ApplicationId { get; set; }
        [DisplayName("Application")]
        public string Name { get; set; }
        public List<DashboardEntry> DashboardEntries { get; set; }
    }

public class Cluster
    {
        [DisplayName("Cluster")]
        public int ClusterId { get; set; }
        [DisplayName("Cluster")]
        public string Name { get; set; }
    }

[Bind(Exclude = "AlbumId")]
    public class DashboardEntry
    {
        [ScaffoldColumn(false)]
        public int DashboardEntryId { get; set; }        
        public int ClusterId { get; set; }        
        public int ApplicationId { get; set; }        
        public HealthStatusIndicator Status { get; set; }
        public string Incident { get; set; }
        public string Remarks { get; set; }

        public virtual Cluster Cluster { get; set; }
        public virtual Application  Application { get; set; }
    }

索引动作方法如下

public ActionResult Index()
        {
            //var dashboardEntries = db.DashboardEntries.Include(d => d.Application).Include(d => d.Cluster);

            var dashboardEntries = db.DashboardEntries
                                   .Include(d => d.Application)
                                   .Include(d => d.Cluster)                                   
                                   .GroupBy(d => d.Application);

            return View(dashboardEntries.ToList());
        }

在视图中,模型声明如下。

@model IEnumerable<HealthCheckIndex.Models.DashboardEntry>

我遇到了一个错误

传入字典的模型项是类型 'System.Data.Entity.Infrastructure.DbQuery1[System.Linq.IGrouping2[HealthCheckIndex.Models.Application,HealthCheckIndex.Models.DashboardEntry]]', 但是这本字典需要一个类型的模型项 'System.Collections.Generic.IEnumerable`1[HealthCheckIndex.Models.DashboardEntry]'。

如果我在如下视图中更改模型声明,我会收到另一个错误,Cluster 不可访问。

@model IEnumerable>

我想将仪表板条目分组到不同的应用程序中,并通过从每个组中选择最大仪表板条目来过滤组。

【问题讨论】:

  • 最好不要将 EF 模型直接传递给您的视图。创建一个 ViewModel,其中包含控制器创建并传递给您的 View 的不带导航属性的数据
  • 感谢您的建议。我最终会改用这种方法,但现在我的目标是让应用程序启动并运行。我现在要选择 SelectMany(c=>c)

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


【解决方案1】:

您当前传递给视图的类型与指定的类型不匹配

@model IEnumerable<HealthCheckIndex.Models.DashboardEntry>

目前您正在传递的内容类似于字典,其中键是 Application,值是 HealthCheckIndex.Models.DashboardEntry 的 IEnumerable

为了做到这一点,您有以下两种选择之一:

  1. 将控制器动作的最后一行替换为

    return View(dashboardEntries.SelectMany(c=&gt; c).ToList());

  2. 更改视图中的模型定义以匹配您返回的列表

【讨论】:

  • 感谢 SelectMany(c=>c)。它返回分组到应用程序中的所有记录。如何根据每个组的最大 dashboardEntryId 过滤组?
  • 只使用以下“Select(c=> c.Max(x=> x.DashboardEntryId))”代替 SelectMany
  • 谢谢。我遇到了这个stackoverflow.com/questions/470440/…,这似乎也解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 2019-01-17
  • 1970-01-01
相关资源
最近更新 更多