Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core Web Api, Json Object not return child objects in Complex object

I have Asp.Net core 3.1 Web Api where a complex object sould be returned by an action like a Json, the problem is that the returned object does not contain the list of child objects:

Below the object:

public class DepartementViewModel
{
    public int Dep_ID { get; set; }
    public string Dep_Name { get; set; }

    public List<BasicEmpViewModel> listEmployees = new List<BasicEmpViewModel>();
}

And the Action

[HttpGet]
public async Task<ActionResult<IEnumerable<DepartementViewModel>>> GetDepartement()
{
    IRepository IRepos = new DepartementRepository(_context);
    IList<DepartementViewModel> ilIst = await IRepos.GetList();
    return Ok(ilIst);
}

The repository GetList function

public async Task<IList<DepartementViewModel>> GetList()
{
    IList<DepartementViewModel> listDept = new List<DepartementViewModel>();
    listDept = await(from dept in _context.Departement                        
                          orderby dept.Dep_ID ascending
                              select new DepartementViewModel
                              {
                                  dept.Dep_ID ,
                                  dept.Dep_Name
                              }
                     ).ToListAsync();

    listDept.ForEach(x =>
    {       
        var emObj =_context.Employee;
        foreach (Employee E in emObj)
        {
            E.listEmployees.Add(new BasicEmpViewModel()
                                    {
                                        Emp_ID = E.Emp_ID,
                                        Emp_Name = E.Emp_Name,
                                        Checked = (E.Dep_ID == x.Dep_ID) ? true : false
                                    }
                                );
        }
    }); 

    return listDept;
}

The returned Json object does not contain the list of employees "listEmployees", it just displays information relating to the main object :Dep_ID and Dep_Name.

Is there something missing in my code ?.

Thank you

like image 765
devjelop anje Avatar asked Aug 29 '26 18:08

devjelop anje


1 Answers

I have found the solution, I publish the solution for any such problem. indeed it is necessary to put a Getter and Setter for the property listEmployees in the class DepartementViewModel like below

public class DepartementViewModel
{
    public int Dep_ID { get; set; }
    public string Dep_Name { get; set; }

    public List<BasicEmpViewModel> listEmployees {get; set; };
}

Cordially

like image 197
devjelop anje Avatar answered Sep 01 '26 08:09

devjelop anje