在列表中用列表填充POCO对象

本文关键字:列表 POCO 对象 填充 | 更新日期: 2023-09-27 17:57:49

我试图填充一个POCO对象,但在"objectAreas.position.Add(objectPositions);"行,我得到了NullReferenceException-对象引用未设置为对象实例,我认为我初始化得不好,但我没有看到错误,让我们看看代码:

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
     }

区域存储库

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

如果你能给我任何帮助/指导,我将不胜感激,谢谢。

在列表中用列表填充POCO对象

您从未初始化objectAreas.position,因此List<T>的默认值为null

由于您试图在null引用上调用Add方法,因此会得到一个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>();
    }
}

你不应该像下面这样做吗。您的positionnull,原因尚未初始化,因此出现上述异常。

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