动态LinqToSQL数据透视表查询

时间:2009-06-11 21:18:46

标签: asp.net asp.net-mvc linq-to-sql

http://img7.imageshack.us/img7/3050/downtime.png

我有两个日历选择器(To和From)我需要构建Year1 - > 4动态地。我也获得了有关2006年和2009年价值的1件商品的重复记录。如果他们也想要,他们可以选择100年。检查附图。

  public ActionResult DownTimeSummaryTabular(int Start,int End)
    {
        var q = from item in new iSppms.Models.iSppmsDataContext().Incidents
                group item by new
                {
                    item.Supplier.Id,
                    item.Supplier.Name,
                    item.SupplierPlant,item.DownTime
                }
                    into supplier
                    select new
                    {
                        SupplierId = supplier.Key.Id,
                        SupplierName = supplier.Key.Name,
                        SupplierPlant = supplier.Key.SupplierPlant.Plant,
                        Years = from incident in supplier
                                let year = incident.IncidentDate.Year
                                where year <= End and year >= Start
                                group incident by year into incidentForYear
                                select incidentForYear.DownTime
                    };

        return View();
    }

1 个答案:

答案 0 :(得分:0)

我的眼睛!我希望我有能力进行编辑。

这是我解决问题的方法:

// This should be in your controller
var q = from item in new iSppms.DataAccess.IncidentRepository()
        group item by new { 
            item.Supplier.Id, 
            item.Supplier.Name, 
            item.Supplier.Plant } 
        into supplier 
        select new {
          SupplierId = supplier.Key.Id,
          SupplierName = supplier.Key.Name,
          SupplierPlant = supplier.Key.Plant,
          Years = from incident in supplier
                  let year = incident.IncidentDate.Year
                  where year <= EndYear and year >= StartYear
                  group incident by year into incidentForYear
                  select incidentForYear.DownTime.ToIntOrDefault()
        }

<%        
 foreach (var row in q)
 { %>
            <tr>
                <td>
                    <%= incident.SupplierName %>
                </td>
                <td>
                    <%= incident.SupplierPlant %>
                </td>
  <% for(var y = StartYear; y < EndYear; ++y) 
     { 
        var year = row.Years[y]; %>                
                <td>
                    <%= year.Sum() %>
                </td>
<% } %>                
            </tr>
 <% } %>

这是使转换效果更好的扩展方法。

 public static int ToIntOrDefault(this string value)
 {
  int result;
  Int32.TryParse(value, out result);
  return result;
 }

请注意,您的视图中的代码太多了。选择显示内容的工作应该在控制器中完成,包括转换为int。视图应该盲目地迭代集合(有人可能会认为“Sum()”也应该在控制器中完成)。