[英]Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`
[英]Cast EF DBquery to Viewmodel - Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery
我有一个对结果进行分组的实体框架查询,我想将它传递给视图,但我无法将它正确地投射到视图模型! (我想在视图中的网格中显示结果)
如果我使用这个演员
viewModel.Groupeds = (IEnumerable<Grouped>) result;
我收到这些错误 Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType4
2[System.Nullable`1[System.Int32],System.Int32]]' to type
我应该怎么投?
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; }
}
该代码创建了一个匿名类型的IEnumerable
,您应该创建Grouped
结果的IEnumerable
。 请注意,虽然您创建的匿名类型和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()
),因为如果上下文处理,在视图生成之前,它会导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.