【发布时间】:2020-10-05 12:43:29
【问题描述】:
我有 Asp.Net core 3.1 Web Api,其中一个复杂的对象应该由 Json 之类的操作返回,问题是返回的对象不包含子对象列表:
物体下方:
public class DepartementViewModel
{
public int Dep_ID { get; set; }
public string Dep_Name { get; set; }
public List<BasicEmpViewModel> listEmployees = new List<BasicEmpViewModel>();
}
还有行动
[HttpGet]
public async Task<ActionResult<IEnumerable<DepartementViewModel>>> GetDepartement()
{
IRepository IRepos = new DepartementRepository(_context);
IList<DepartementViewModel> ilIst = await IRepos.GetList();
return Ok(ilIst);
}
仓库GetList函数
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;
}
返回的 Json 对象不包含员工列表“listEmployees”,它只显示与主要对象相关的信息:Dep_ID 和 Dep_Name。
我的代码中是否缺少某些内容?
谢谢
【问题讨论】:
-
你使用EF吗?您是否忘记了检索数据的方法中的
Include员工? docs.microsoft.com/en-us/ef/core/querying/related-data -
员工列表key的jsonarray是listEmployees吗?
-
我没有使用 include 但我使用 Linq 请求来填充对象并且对象填充良好但它没有在 Json 对象中显示列表“listEmployees”
-
显示
IRepos.GetList代码 -
在转换为json之前,你能调试一下“ilist”是否包含任何雇员吗?
标签: c# asp.net-mvc asp.net-core asp.net-core-webapi