NullReferenceException on trying to enumerate an empty IQueryable
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.D开发者_运维问答eptId) && (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.
Is p.Department can be null?
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();
精彩评论