将多个分组的结果传递给View

时间:2014-07-04 16:31:49

标签: asp.net-mvc linq entity-framework asp.net-mvc-4

Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList()

如何将此代码的结果传递给View?代码有效。什么类型必须有View?

var Deliveries = Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList(); //It`s Ok.

List<IGrouping<{Crew:Crew, Date:DateTime}, Delivery>> Deliveries = Db.Deliveries.Where(d => d.CrewId != null).GroupBy(d => new {d.Crew, d.Date}).OrderBy(d => d.Key).ToList(); //It`s wrong.

List<IGrouping<{Crew, DateTime}, Delivery>> //This type is wrong too.

或者是否存在此问题的任何解决方案,而不使用匿名类型?

抱歉我的英语不好,谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

因为您在GroupBy中使用匿名类型,结果类型只是虚拟存在。 使用

@model dynamic

或为结果定义类型

public class GroupedDelivery{
    public Crew Crew {get;set;}
    public DateTime Date  {get;set;}
    public List<Delivery> Deliveries {get;set;}
}

在GroupBy之后的Select中映射类型。

List<GroupedDelivery> Deliveries = Db.Deliveries.Where(d => d.CrewId != null)
            .GroupBy(d => new {d.Crew, d.Date})
            .Select(p => new GroupedDelivery{
                    Crew = p.Key.Crew,
                    Date = p.Key.Date,
                    Deliveries = p.Select(x => x).ToList()
                })
            .OrderBy(d => d.Crew).ThenBy(p => p.Date).ToList();