【发布时间】: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