基于两个相关实体生成json结果

时间:2011-07-07 16:48:49

标签: asp.net-mvc-3 jqgrid

我有两个相关的一个到多个实体

比赛和汽车(比赛中有很多车)

我需要生成一个json结果将它传递给jQGrid,我想可能是这样做而不创建新的类将包含属性。我以为我可以那样:

var jsonData = new
        {
            total = totalPages,
            page = page,
            records = totalRecords,

            rows = (from c in Races
                    select new
                    {
                        //c.Cars.Id.ToString(),  - need iteration
                        cell = new string[] {
                                 //c.Cars.Id.ToString(),  - need iteration
                                 c.Date.ToString(),
                                 c.Type.ToString(),
                                 c.Cars //But how i may loop all Cars colection here?
                                 //c.Cars.Name - need iteration
                                 //c.Cars.Speed - need iteration
                             }
                    }).ToArray()
        };

但Cars属性代表集合。我怎么可能迭代内部集合初始化器?或者我应该更好地创建类女巫将包含我需要的所有属性?

有什么想法吗?

让我们说Car有属性Name Speed Id和Race有属性Date,Type

数据将显示如下:

Date       |  Type | Id  | Name      | Speed
02/03/2011 |   A   |  1  | MegaName1 |  130
02/03/2011 |   A   |  2  | MegaName2 |  112
02/03/2011 |   A   |  3  | MegaName3 |  132
03/05/2011 |   B   |  4  | MegaName2 |  112
03/05/2011 |   B   |  5  | MegaName4 |  33

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

var jsonData = new
{
    total = totalPages,
    page = page,
    records = totalRecords,

    rows = 
        (from race in races
         from car in race.Cars
         select new
         {
            cell = new string[] 
            {
                race.Date.ToString(),
                race.Type,
                car.Id,
                car.Name,
                car.Speed.ToString()
            }
         }).ToArray()
};