0

我正在尝试创建一个 linQ 查询,它将产生与此 SQL 相同的结果:

SELECT Priority.PriorityKey, Count(Priority.PriorityKey) AS NewPresentingUnits
FROM Priority INNER JOIN SupportPeriod ON Priority.PriorityCode = SupportPeriod.PriorityCode
WHERE (((SupportPeriod.NewClient)=True) AND ((SupportPeriod.DateAssistanceRequested) Between #1/1/2013# And #2/1/2013#) AND ((SupportPeriod.DateFinished) Between #1/1/9999# And #12/31/9999#))
GROUP BY Priority.PriorityKey;

当我运行 SQL 查询时,我得到以下结果:

https://docs.google.com/file/d/0B6b_N7sDgjmvRlBtT1lZWURERVU/edit?usp=sharing

这是 linQ 语句:

    SupportPeriodTableAdapter spTa = new SupportPeriodTableAdapter();
    SupportPeriodDataTable dataTables = spTa.GetData();
        var test = (from sp in dataTables
                  where (sp.NewClient == true) &&
                      (sp.DateAssistanceRequested >= new DateTime(2013, 1, 1) &&
                      sp.DateAssistanceRequested <= new DateTime(2013, 2, 1)) &&
                      (sp.DateFinished > new DateTime(2013, 2, 1))
                  group sp by sp.PriorityRow.PriorityKey into groupz
                  select new { Key = groupz.Key, sount = groupz.Count() });

当我尝试调试时,var test我在结果视图中得到“对象引用未设置为对象的实例”。

https://docs.google.com/file/d/0B6b_N7sDgjmvdGp0bjJCNkE3TTg/edit?usp=sharing

我不熟悉使用 linQ 的“分组依据”和“选择新”功能,因此我很难弄清楚这一点....

4

1 回答 1

0

我认为您的数据加载有问题。

我将检查 dataTables 中的所有行是否都有 PriorityRow

如果有一些行上没有 PriorityRow,则 group by 失败。在这种情况下,您可以将 linq 更改为:

 var test = (from sp in dataTables
             where (sp.NewClient == true) &&
                   (sp.DateAssistanceRequested >= new DateTime(2013, 1, 1) &&
                    sp.DateAssistanceRequested <= new DateTime(2013, 2, 1)) &&
                   (sp.DateFinished > new DateTime(2013, 2, 1))
             group sp by sp.PriorityRow != null 
                               ? sp.PriorityRow.PriorityKey 
                               : "not key"
                      into groupz
             select new { Key = groupz.Key, sount = groupz.Count() });

使用: 按 sp.PriorityRow != null 对 sp 进行分组?sp.PriorityRow.PriorityKey :“不是关键”进入 groupz

于 2013-04-08T03:34:25.800 回答