CallumVass
CallumVass

Reputation: 11448

LINQ / EF - Using GroupBy to return values to a View

In my MVC 3 application I'm using the following query:

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

Then in my view I have this at the top:

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

But this throws an error:

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]'.

How do I use a group by in this case? As I'd like to group each of my QuoteLines to their matching VehicleID

Edit

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

Vehicles Model:

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

I think I have this setup correctly, but each Vehicle can have a collection of QuoteLines attached to it!

Upvotes: 1

Views: 1817

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

The model type is different from the type returned by the function .I think that the appropriate model for this view is

@model IEnumerable<IGrouping<int, DayBookQuoteLines>> 

and there is no need for the ToList at the query

Upvotes: 4

Related Questions