0

当我尝试检索一些数据时出现此错误。这是我查询的方式

   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 =...

4

2 回答 2

3

.SingleOrDefault() 在没有找到记录时返回 null,并且在下一个语句中,您使用“标准”,就好像它从不为 null。

但这只是众多可能原因之一...

于 2012-05-03T13:38:07.083 回答
1

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

于 2012-05-03T13:39:05.980 回答