为什么我有这个错误NullReferenceException

时间:2014-04-14 10:44:19

标签: c# linq

为什么在FundList.children.Add(基金)上有这个错误?

  

发生了'System.NullReferenceException'类型的异常   ICRC.HRSSD.BAL.dll但未在用户代码中处理

我的模型“TaskTree”是一个有id,名字和孩子的类,孩子是其他TaskTree的列表...我需要这样做,因为我必须做一棵树......

    public List<TaskTree> getTaskTree(int IdTeam)
    {
        using (HRSSD_DATA context = new HRSSD_DATA())
        {
         List<TaskTree> ListAll = new List<TaskTree>();

            var person = context.AR_PERSON.Where(a => a.STATUS == "A" && a.CR_GROUP.REF==IdTeam).ToList();
            foreach (var item in person)
            {
                TaskTree FundList = new TaskTree();
                FundList.id = item.REF;
                FundList.name = item.FULL_NAME;

                var task = context.TASK.Where(a => a.IdCurrentOfficer == item.REF && a.BASE_ENTITY_TYPE == 100 && a.OPEN_IND == 1 && a.ACTIVE_TASK == 1 && a.TEMPLATE_IND == 0&& a.TASK_STATUS_REF != 114).ToList();
                foreach (var tasks in task)
                {
                    TaskTree Fund = new TaskTree();
                    Fund.name = tasks.TASK_TITLE;
                    Fund.id = tasks.TASK_NO;

                    FundList.children.Add(Fund);

                }

                ListAll.Add(FundList);
            }
            return ListAll;
        }
    }

和我的TaskTree类

public class TaskTree
{
    public int id;
    public string name;
    public List<TaskTree> children;
}

1 个答案:

答案 0 :(得分:1)

请尝试使用以下代码段。

public List<TaskTree> getTaskTree(int IdTeam)
{
    using (HRSSD_DATA context = new HRSSD_DATA())
    {
        List<TaskTree> ListAll = new List<TaskTree>();

        var person = context.AR_PERSON.Where(a => a.STATUS == "A" && a.CR_GROUP.REF == IdTeam).ToList();
        if (person != null)
        {
            foreach (var item in person)
            {
                TaskTree FundList = new TaskTree();
                FundList.id = item.REF;
                FundList.name = item.FULL_NAME;

                var task = context.TASK.Where(a => a.IdCurrentOfficer == item.REF && a.BASE_ENTITY_TYPE == 100 && a.OPEN_IND == 1 && a.ACTIVE_TASK == 1 && a.TEMPLATE_IND == 0 && a.TASK_STATUS_REF != 114).ToList();

                if (task != null)
                {
                    // Please check below line of code 
                    FundList.children = new List<TaskTree>();

                    foreach (var tasks in task)
                    {
                        TaskTree Fund = new TaskTree();
                        Fund.name = tasks.TASK_TITLE;
                        Fund.id = tasks.TASK_NO;

                        FundList.children.add(Fund);

                    }
                }
                ListAll.Add(FundList);
            }
        }
        return ListAll;
    }
}