方法在返回非空值后抛出空引用异常。

3
我有一个服务方法,非常简单地获取数据库中所有商店的信息。它使用Auto Mapper从EF映射商店,并返回StoreDTO(一个简单的POCO)类型的通用响应。
问题在于:这个方法执行得非常好,我一直跟踪到最后。response中的每个属性都有值,没有任何一个是null。列表中填充了项目,列表中的项目是有效的等等。
但是当GetAllStores返回时,以下代码会抛出NullReferenceException异常:
ListResponseDTO<StoreDTO> allStores = Services.Stores.Stores.GetAllStores();

编辑:这是调试器的截图,当它返回时。您可以在监视窗口中看到值看起来正常:http://i.imgur.com/rd853.png

非常感谢任何帮助。这是该方法的代码:

    public static ListResponseDTO<StoreDTO> GetAllStores()
    {
        ListResponseDTO<StoreDTO> response = new ListResponseDTO<StoreDTO>("Get Stores not successful");

        try
        {
            response.Items = new List<StoreDTO>();
            using (DomainEntities db = new DomainEntities(Global.ConnectionString))
            {
                foreach (var IndividualStore in db.Stores)
                {
                    Mapper.CreateMap<Store, StoreDTO>();
                    var IndividualStoreDTO = Mapper.Map<Store, StoreDTO>(IndividualStore);
                    response.Items.Add(IndividualStoreDTO);
                }
            }
            response.Message = "Store(s) retrieved successfully";
            response.Success = true;
        }
        catch (Exception ex)
        {
            Logging.Log("Get All Stores", response.Message + " " + ex.ToString(), Logging.LogPriority.Error, "Store Operations");
        }
        return response;
    }

以下是通用DTO的定义:

public class ListResponseDTO<DtoType> : ResponseDTO
{
    public ListResponseDTO()
        : base()
    {
        Items = new List<DtoType>();
    }

    public ListResponseDTO(string defaultMessage)
        : base(defaultMessage)
    {
        Items = new List<DtoType>();
    }

    public List<DtoType> Items;
}

如果您有疑问,ResponseDTO 有两个属性:

bool Success

string Message

这里是异常细节,恐怕对您没有太大帮助:

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=Infinity
  StackTrace:
   at PLM.Infinity.Default.GetDrawersForUser() in C:\Users\jlucas\Documents\Visual Studio 2010\PLM Source Control\Utilities\InfinityInterface\Infinity\Default.aspx.cs:line 96
  InnerException: 

3
尝试移除 try/catch 并观察发生了什么。 - John Saunders
1
@DJKRAZE:GetAllStores 方法是第二段代码。 - Ry-
1
你能发布异常的完整堆栈跟踪吗? - Chris Dunaway
1
你能展示一下你在哪里调用了 Services.Stores.Stores.GetAllStores() 吗?堆栈跟踪中的内部异常有没有提示,或者它实际上是停在那里的? - Chris
2
据推测,GetDrawersForUser() 方法中包含 ListResponseDTO<StoreDTO> allStores = Services.Stores.Stores.GetAllStores(); 这一行代码?同时,我猜测从你的截图中可以看出,当你在这个位置点击“步过”并返回到父级时,它立即抛出错误?有没有可能看到更多 GetDrawersForUser() 方法的内容,以了解是否与您调用它的方式有关? - Chris
显示剩余12条评论
1个回答

0

你能加一个where子句,只返回你确定所有字段都存在的商店,看看问题是否仍然存在吗?

有时候会发生这种情况,因为在数据集中的某个地方,你缺少了数据,在调试过程中你没有看到它。

你也可以再尝试一下捕获Mapper调用的异常,看看那里是否出现了问题。

这些只是建议,而不是答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接