尝试枚举空IQueryable时出现NullReferenceException

时间:2009-11-08 12:43:27

标签: c# .net linq linq-to-entities

当我尝试将以下LINQ转换为EF查询时,我收到NullReferenceException。这可能有什么问题?

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

编辑:我刚刚发现我太快了,我的部门标准是空的。

2 个答案:

答案 0 :(得分:3)

p.Department是否可以为空?

答案 1 :(得分:0)

除了访问可以为null的对象的属性(p.Departmentdept都可以为null)之外,您还要实例化一个永远不会被使用的新List<DailyProductionRecord>。所以你的例子可以这样写:

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