LINQ / EF - 使用GroupBy将值返回给View

时间:2012-05-08 11:02:18

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

在我的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

修改

QuoteLines Model:

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; }
}

我认为我已正确设置此设置,但每辆车都可以附加一系列QuoteLines!

1 个答案:

答案 0 :(得分:4)

模型类型与函数返回的类型不同。我认为此视图的适当模型是

@model IEnumerable<IGrouping<int, DayBookQuoteLines>> 

并且查询中不需要ToList