views:

454

answers:

2

I have a Null Reference Exception Caused by this code:

var recentOrderers = (from p in db.CMS
            where p.ODR_DATE > DateTime.Today - new TimeSpan(60, 0, 0, 0)
            select p.SOLDNUM).Distinct();
result = (from p in db.CMS
             where p.ORDER_ST2 == "SH" &&
                   p.ODR_DATE > DateTime.Today - new TimeSpan(365, 0, 0, 0) &&
                   p.ODR_DATE < DateTime.Today - new TimeSpan(60, 0, 0, 0) &&
                   !(recentOrderers.Contains(p.SOLDNUM))/**/
             select p.SOLDNUM).Distinct().Count();

result is of double type. When I comment out:

!(recentOrderers.Contains(p.SOLDNUM))

The code runs fine. I have verified that recentOrderers is not null, and when I run:

if(recentOrderes.Contains(0)) return;

Execution follows this path and returns. Not sure what is going on, since I use similar code above it:

var m = (from p in db.CMS where p.ORDER_ST2 == "SH" select p.SOLDNUM).Distinct();
            double result = (from p in db.CUST
                        join r in db.DEMGRAPH on p.CUSTNUM equals r.CUSTNUM
                        where p.CTYPE3 == "cmh" && !(m.Contains(p.CUSTNUM)) &&
                              r.ColNEWMEMBERDAT.Value.Year > 1900
                        select p.CUSTNUM).Distinct().Count();

which also runs flawlessly. After noting the similarity, can anyone help? Thanks in advance.

A: 

I'm not super familiar with Linq, but could it be that .Distinct() returns null if there are no matching results?

Bela
A: 

Try to explicite get data from the first query by converting to a list object (actually: executing it using .ToList()) then use in comparison.

var recentOrderers = (from p in db.CMS
            where p.ODR_DATE > DateTime.Today - new TimeSpan(60, 0, 0, 0)
            select p.SOLDNUM).Distinct().ToList();
twk
That works! Though I still don't understand the difference. Especially since it works in one section and not the next.
Frank
Because in your example your first query is a type of IQueryable which is not a real value itself - it is just a query definition.And it is not good idea to treat query definition as data ;-)Try to avoid 'var' and use concrete types in the future to avoid such a problems.
twk
Use of var has nothing to do with this. It's still strongly typed.
Robaticus