将EF DBquery转换为Viewmodel - 无法转换类型为System.Data.Entity.Infrastructure.DbQuery的对象

时间:2015-08-29 11:57:47

标签: c# entity-framework

我有一个实体框架查询对结果进行分组,我想将其传递给视图,但我无法将其正确地投射到viewmodel! (我想在视图中的网格中显示结果)

如果我使用此演员

 viewModel.Groupeds = (IEnumerable<Grouped>) result;

我收到这些错误 无法转换'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType4 2 [System.Nullable`1 [System.Int32],System.Int32]]'类型的对象以输入

我应该如何施展它?

public ActionResult Show(int? id)
    {
       IEnumerable<dynamic> result = db.StatData
             .GroupBy(k => new { k.QuestId, k.OptionId })
             .Select(c => new
             {
                 OptionId = c.Select(q => q.OptionId).FirstOrDefault(),
                 Counted = c.Select(q => q.id).Count(),
             });

             var viewModel = new StatsView();
             viewModel.Groupeds = (IEnumerable<Grouped>) result;
    return View(viewModel);
}

public class StatsView
{
    public IEnumerable<Grouped> Groupeds { get; set; }
}


public partial class Grouped
{
    public Nullable<int> Counted { get; set; }
    public Nullable<int> OptionId { get; set; }
}

1 个答案:

答案 0 :(得分:2)

代码会创建IEnumerable个匿名类型,您应该创建IEnumerableGrouped个结果。请注意,尽管您创建的匿名类型和Grouped具有相同的属性,但它们是不同的类型,并且无法将它们相互转换。

public ActionResult Show(int? id)
{
   //defining result as var is sufficient 
   var result = db.StatData
         .GroupBy(k => new { k.QuestId, k.OptionId })
         .Select(c => new Grouped//<<-here
         {
             OptionId = c.Select(q => q.OptionId).FirstOrDefault(),
             Counted = c.Select(q => q.id).Count(),
         }).ToList();//commit the query
         var viewModel = new StatsView();
         viewModel.Groupeds = result;//No need for casting
   return View(viewModel);
}

最好在将查询发送到视图之前提交查询(即ToList()),因为如果上下文处理,则在视图生成之前,它会导致错误。