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
Includeemployees at method which retrieve data? learn.microsoft.com/en-us/ef/core/querying/related-dataIRepos.GetListcode