简体   繁体   中英

linQ group by/select - object reference not set to an instance of an object

I'm trying to create a linQ query which will yield the same outcome as this 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;

I get the following result when i run the SQL query:

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

This is the linQ statement:

    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() });

When i try to debug var test i get "object reference not set to an instance of an object" in the results view.

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

I'm new to using 'group by' and 'select new' features of linQ, thus i'm having a hard time figuring this out....

I think there are something going wrong with your data load.

I will check if all rows in dataTables have PriorityRow

if there are some rows does not have PriorityRow on it, the group by with fail. in this case, you can change your linq to:

 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() });

use: group sp by sp.PriorityRow != null ? sp.PriorityRow.PriorityKey : "not key" into groupz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM