2016-07-20 75 views
0

我試圖填充一個POCO對象,但我得到NullReferenceException - 對象引用未設置爲對象實例,在行「objectAreas.position.Add(objectPositions) ;「我想我不會初始化很好,但我沒有看到我的錯誤,讓我們來看看代碼:在列表中填充POCO對象和列表

POCO對象

public class GenericQuery 
{ 
    public sealed class Areas 
    { 
     public int idarea { get; set; } 
     public string areaname { get; set; } 
     public List<Positions> positions { get; set; } 
    } 

    public sealed class Positions 
    { 
     public int idposition { get; set; } 
     public string positionname { get; set; } 
    } 

    public sealed class QueryAreasPositions 
    { 
     public int code { get; set; } 
     public string response { get; set; } 
     public List<Areas> areas { get; set; } 
    } 
} 

加油吧

GenericQuery.QueryAreasPositions objectAreasPositions = new GenericQuery.QueryAreasPositions(); 

var query = areaRepository.Get(); //Eager Loading EntityFramework List Object, see the AreaRepository at the end 

objectAreasPositions.code = 123; 
objectAreasPositions.response = "anything"; 

foreach (var area in query) 
    { 
     GenericQuery.Areas objectAreas = new GenericQuery.Areas(); 
     objectAreas.idarea = area.IdArea; 
     objectAreas.areaname = area.Name; 
      foreach (var position in area.Position) 
      { 
       GenericQuery.Positions objectPositions = new GenericQuery.Positions(); 
       objectPositions.idposition = position.IdPosition; 
       objectPositions.positionname = position.Name; 
       ***objectAreas.position.Add(objectPositions);***//HERE 
      } 

     objectAreasPositions.areas.Add(objectAreas); //And maybe here 
    } 

AreaRepository

public List<Area> Get() 
{ 
    using (var context = new Entities()) 
    { 
     return context.Area.Include("Position").ToList(); 
    } 
} 

我希望得到任何幫助/指導你可以給我,謝謝。

+1

objectAreas:

objectAreas.position = new List<GenericQuery.Positions>(); 

或者,您可以GenericQuery.Areas構造函數,它會更合適添加此邏輯.position = new List (); – Gusman

+0

@Gusman,謝謝。 –

回答

1

你永遠初始化objectAreas.position,從而爲List<T>的默認值是null

既然你試圖調用一個null參考Add方法,你得到一個的NullReferenceException

爲了解決這個問題,你應該使用它之前初始化屬性:

public sealed class Areas 
{ 
    public int idarea { get; set; } 
    public string areaname { get; set; } 
    public List<Positions> positions { get; set; } 

    public class Areas() 
    { 
     positions = new List<Positions>(); 
    } 
} 
+0

構造函數選項完美,我接受它,謝謝。 –

0

你不應該像下面那樣做。您的positionnull原因尚未初始化,因此說是異常。

objectAreas.position = new List<Position>(); 
objectAreas.position.Add(objectPositions); 
+0

謝謝,我沒有看到我的錯誤。 –