John S
John S

Reputation: 8351

EF MVC Linq - Error passing model to a MVC WebGrid

When I try to pass the results of a Linq query in to a MVC.Webgrid I am getting the error (simplified):

The model item passed into the dictionary is of 
type'System.Data.Entity.Infrastructure.DbQuery but 
this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[MyModel.Models.MyMetric]'

This is the ActionResult that fails:

 public ActionResult Test()
    {
        var metrics = db.Metrics
            .GroupBy(c => c.Year)
            .Select(g => new
            {
                Year = g.Key,
                Q1 = g.Where(c => c.Quarter == 1).Sum(c => c.Value),
                Q2 = g.Where(c => c.Quarter == 2).Sum(c => c.Value),
                Q3 = g.Where(c => c.Quarter == 3).Sum(c => c.Value),
                Q4 = g.Where(c => c.Quarter == 4).Sum(c => c.Value)
            });                        
        return View(metrics);
    }

I assume that since I am creating a pivot of the original data that I need to create some sort of new model but I am unsure how to do that in this context. (just geting my feet wet with EF and MVC)

Any ideas?

TIA J

Upvotes: 0

Views: 490

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039238

You are passing an anonymous type to the view whereas you should pass an IEnumerable<MyMetric>. So, assuming that MyMetric looks like this:

public class MyMetric
{
    public int Year { get; set; }
    public int Q1 { get; set; }
    public int Q2 { get; set; }
    public int Q3 { get; set; }
    public int Q4 { get; set; }
}

you simply need to return an IEnumerable<MyMetric> from your LINQ query:

public ActionResult Test()
{
    var metrics = db.Metrics
        .GroupBy(c => c.Year)
        .Select(g => new MyMetric
        {
            Year = g.Key,
            Q1 = g.Where(c => c.Quarter == 1).Sum(c => c.Value),
            Q2 = g.Where(c => c.Quarter == 2).Sum(c => c.Value),
            Q3 = g.Where(c => c.Quarter == 3).Sum(c => c.Value),
            Q4 = g.Where(c => c.Quarter == 4).Sum(c => c.Value)
        });                        
    return View(metrics);
}

Upvotes: 3

Related Questions