实体框架无法执行查询:对象引用未设置为对象的实例

时间:2012-05-03 13:36:09

标签: c# .net entity-framework exception-handling linq-to-entities

当我尝试检索某些数据时,我收到此错误。这是我查询的方式

   using (_realtyContext = new realtydbEntities())
   {
                foreach (int yr in years)
                {
                    var standard = (from feest in _realtyContext.FeeStandards
                                    where feest.Year == yr && feest.FeeCategory.CategoryName == "PropertyFee"
                                    select feest).SingleOrDefault();

                    var chargeItem = (from chrgItem in _realtyContext.PropertyFees
                                      where chrgItem.FeeStandardID == standard.FeeStandardID
                                      && chrgItem.HousholdId == Householder.HouseholdID
                                      select chrgItem).SingleOrDefault();

                        this._propertyFees.Add(chargeItem);
                        this._standards.Add(standard);
                }
   }

  

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

     

错误发生在第二个查询。(var chargeItem)

此查询会抛出错误: var chargeItem = ...

2 个答案:

答案 0 :(得分:3)

.SingleOrDefault()在没有找到记录时返回null,在下一个语句中你使用“standard”,好像它永远不会为空。

但这只是众多可能原因中的一个......

答案 1 :(得分:1)

你必须检查标准是否为空。如果没有结果,SingleOrDefault()将返回null

相关问题