Reputation: 47
I have a Entity Framework query who group the result, I want to pass it to view, but I cant cast it correct to the viewmodel! (I want to show the result in a grid in the view)
If I use this cast
viewModel.Groupeds = (IEnumerable<Grouped>) result;
I get these error
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType4
2[System.Nullable`1[System.Int32],System.Int32]]' to type
How should I cast it?
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; }
}
Upvotes: 2
Views: 4173
Reputation: 6696
The code creates an IEnumerable
of anonymous types, you should create IEnumerable
of Grouped
result. Note that although the anonymous type you created and the Grouped
have the same properties, but they are different types and cannot cast them to each other.
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);
}
It is better to commit the query (i.e by ToList()
) before sending it to the view, because if the context disposes, before the view generation, it causes an error.
Upvotes: 2