views:

205

answers:

2

I am getting a NullReferenceException when I try and convert the following LINQ to EF query. What could be wrong here?

            List<DailyProductionRecord> prodRecs = new List<DailyProductionRecord>();
            var recs = from p in productionEntities.DailyProductionRecordSet
                       where ((p.Department.DeptId == dept.DeptId) && (p.RecordDate >= thisPeriodStart) && (p.RecordDate < nextPeriodStart))
                       select p;
            prodRecs = recs.ToList();

EDIT: I've just discovered I was too quick off the mark, and my dept criterion was null.

+1  A: 

Is p.Department can be null?

uvw
Not quite, but dept is null. Close enough.
ProfK
A: 

Aside from accessing properties on objects that can be null (p.Department and dept can both be null), you are also instantiating a new List<DailyProductionRecord> that never gets used. So your example can be written like this:

List<DailyProductionRecord> prodRecs = (from p in productionEntities.DailyProductionRecordSet
                                        where ((p.Department.DeptId == dept.DeptId) && (p.RecordDate >= thisPeriodStart) && (p.RecordDate < nextPeriodStart))
                                        select p).ToList();
Ronald
Thanks @Ronald, but that's how I started off. If was just decomposing this when I used the extra list.
ProfK