0

当我尝试将 Linq 查询的结果传递给 MVC.Webgrid 时,出现错误(简化):

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

这是失败的 ActionResult:

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

我假设因为我正在创建原始数据的一个支点,所以我需要创建某种新模型,但我不确定如何在这种情况下做到这一点。(只是用 EF 和 MVC 弄湿了我的脚)

有任何想法吗?

蒂亚杰

4

1 回答 1

3

您将匿名类型传递给视图,而您应该传递IEnumerable<MyMetric>. 所以,假设MyMetric看起来像这样:

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

你只需IEnumerable<MyMetric>要从你的 LINQ 查询中返回一个:

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);
}
于 2012-06-30T07:42:48.057 回答