c# - Asp.Net Core Web Api,Json 对象不返回复杂对象中的子对象

标签 c# asp.net-mvc asp.net-core asp.net-core-webapi

我有 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。

我的代码中是否缺少某些内容?

谢谢

最佳答案

我找到了解决方案,我发布了任何此类问题的解决方案。确实有必要在 DepartementViewModel 类中为属性 listEmployees 放置一个 Getter 和 Setter,如下所示

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

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

真诚的

关于c# - Asp.Net Core Web Api,Json 对象不返回复杂对象中的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64208845/

相关文章:

javascript - 根据用户位置对谷歌地图中的标记进行排序

c# - 当前上下文中不存在名称 WebHost

asp.net-mvc - ASP.NET MVC 3 中的 Flash 等效项

asp.net-core - 在我的示例 (blazor) 中,为什么绑定(bind)不适用于数组和 for 循环?

c# - 如何解决.net core中Web API构造函数的依赖关系

c# - 在 web.config 上注册一个控件程序集

c# - Console.Write ("H") 和 Console.Write ('H' ) 在 C# 中有什么区别

c# - 使用 JSON.NET JsonTextReader 在 C# 中读取 BigInteger

c# - 为方法声明默认参数时出错

c# - ASP.NET MVC 4 Intranet 模板 - 显示用户全名