开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜