我正在尝试填充POCO对象,但是我得到NullReferenceException - 对象引用未设置为对象的实例,位于“ objectAreas.position.Add(objectPositions); “我认为我没有初始化,但我没有看到我的错误,让我们看看代码:
POCO OBJECT
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();
}
}
我很感激你能给我的任何帮助/指导,谢谢。
答案 0 :(得分:1)
您永远不会初始化objectAreas.position
,因此List<T>
的默认值为null
。
由于您尝试在Add
引用上调用null
方法,因此您收到 NullReferenceException 。
要解决此问题,您应该在使用之前初始化该属性:
objectAreas.position = new List<GenericQuery.Positions>();
或者,您可以在GenericQuery.Areas
构造函数上添加此逻辑,这更合适:
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>();
}
}
答案 1 :(得分:0)
你不应该像下面这样做。您的position
null
原因尚未初始化,因此也就是所述异常。
objectAreas.position = new List<Position>();
objectAreas.position.Add(objectPositions);