2012-02-20 86 views
3

我有一個服務方法,它可以非常簡單地獲取數據庫中所有存儲的信息。它使用Auto Mapper映射EF的商店,並返回類型爲StoreDTO(簡單POCO)的通用響應。返回非空值後拋出空引用異常

問題是這樣的:該方法執行得很好,我一直走到最後。 response中的每個屬性都有一個值,沒有任何值爲空。該列表填充項,在列表中的項目是有效的,等等等等

但下面的代碼,只要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

以下是異常的詳細信息,恐怕這不是太大的幫助:

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並查看會發生什麼 – 2012-02-20 14:37:58

+0

同樣的事情。它不會在方法中拋出異常,它只會在方法返回後拋出異常。 – lucrativelucas 2012-02-20 14:42:02

+0

GetAllStores方法看起來像返回後返回Null的唯一方式是因爲您要麼重新創建它,要麼您有一些奇怪的遞歸方法/屬性調用來重置對象,爲什麼需要此行ListResponseDTO 響應= new ListResponseDTO (「Get Stores not successful」); – MethodMan 2012-02-20 14:55:27

回答

0

你可以把一個where子句,所以你只返回是確保他們有各個領域的商店,看看問題是否仍然存在?

有時會發生這種情況,因爲在您的數據集中某處存在缺失數據,而在調試期間您看不到它。

你也可以把另一個試圖捕獲的盒子的Mapper調用,看看有沒有發生的事情。

這是更多的建議,然後一個答案。