Skip to main content
 首页 » 编程设计

c#之LINQ/EF之使用 GroupBy 将值返回给 View

2024年02月20日25dyllove98

在我的 MVC 3 应用程序中,我使用以下查询:

var items = context.QuoteLines.Include("DaybookVehicles").Where(x => x.EnquiryID == id).GroupBy(x=>x.VehicleID).ToList(); 
return View(items); 

然后在我看来我在顶部有这个:

@model IEnumerable<myApp.Areas.DayBook.Models.DayBookQuoteLines> 

但这会引发错误:

The model item passed into the dictionary is of type 
'System.Collections.Generic.List`1[System.Linq.IGrouping`2[System.Int32,myApp.Areas.DayBook 
.Models.DayBookQuoteLines]]', but this dictionary requires a model item of type  
'System.Collections.Generic.IEnumerable`1[myapp.Areas.DayBook.Models.DayBookQuoteLines]'. 

在这种情况下如何使用分组依据?因为我想将我的每个 QuoteLines 分组到它们匹配的 VehicleID

编辑

报价行模型:

public class DayBookQuoteLines 
{ 
    [Key] 
    public int QuoteLineID { get; set; } 
 
    public int EnquiryID { get; set; } 
 
    public virtual int VehicleID { get; set; } 
 
    public virtual DaybookVehicles Vehicle { get; set; } 
 
    [Required(ErrorMessage = "This field is required.")] 
    [Display(Name = "Item Number:")] 
    [MaxLength(50)] 
    public string ItemNumber { get; set; } 
 
    public string ItemDescription { get; set; } 
} 

车辆型号:

public class DaybookVehicles 
{ 
    [Key] 
    public int VehicleID { get; set; } 
 
    public int EnquiryID { get; set; } 
 
    public virtual ICollection<DayBookQuoteLines> QuoteLines { get; set; } 
 
    public string vrm { get; set; } 
 
    public string make { get; set; } 
 
    public string model { get; set; } 
 
    public string engine_size { get; set; } 
 
    public string fuel { get; set; } 
} 

我想我的设置是正确的,但每个 Vehicle 都可以附加一个 QuoteLines 集合!

请您参考如下方法:

模型类型与函数返回的类型不同。我认为适合这个 View 的模型是

@model IEnumerable<IGrouping<int, DayBookQuoteLines>>  

并且在查询时不需要 ToList