簡體   English   中英

LINQ EF分組和包含例外

[英]LINQ EF Grouping and Include exception

在創建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>

我想將儀表板條目分為不同的應用程序,並通過從每個組中選擇最大儀表板條目來過濾組。

您當前傳遞給視圖的類型與指定的類型不匹配

@model IEnumerable<HealthCheckIndex.Models.DashboardEntry>

當前,您正在傳遞類似字典的內容,其中的鍵是Application,值是HealthCheckIndex.Models.DashboardEntry的IEnumerable。

為了使它具有兩個選項之一:

  1. 將控制器操作的最后一行替換為

    return View(dashboardEntries.SelectMany(c=> c).ToList());

  2. 在視圖中更改模型定義以匹配返回的列表

暫無
暫無

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

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