【问题标题】:.Net Core Web API - How Do I Populate a DTO That Contains a Generic List.Net Core Web API - 如何填充包含通用列表的 DTO
【发布时间】:2021-01-14 00:45:48
【问题描述】:

我的数据模型由 Employee 表和 Projects 表之间的一对多关系组成。我需要我的 DTO 返回一个包含 Project 对象集合/列表的 Employee 对象。我正在使用存储库模式从数据库返回数据。问题 1:如何填充 DTO 的 List 属性?问题2:我的方法正确吗?问题 3:我将 Project 对象列表作为 IEnumerable 返回。我的 DTO 中的 Projects 属性应该是 List、IList、Collection 吗?这是我的代码。提前谢谢你。

//My DTO
public class EmployeeReadDto
{
    public int Id { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string Email { get; set; }
    public ICollection<Project> Projects { get; set; }
}

//GetAll signature from my generic repository
public IEnumerable<T> GetAll()

//Controller where I am trying to populate DTO
[HttpGet("{id}", Name = "employee/GetById")]
public ActionResult<EmployeeReadDto> GetById(int id)
{
    var projects = _projectRep.GetAll();
    var employee = _employeeRep.GetById(id);

    var dto = new EmployeeReadDto
    {
        Id = employee.Id,
        FName = employee.FName,
        LName = employee.LName,
        Email = employee.Email,
        Projects = projects
    };

    return Ok(dto);
}

【问题讨论】:

    标签: asp.net-core-webapi data-transfer-objects


    【解决方案1】:

    问题 1:如何填充 DTO 的 List 属性?题 2:我的方法正确吗?问题3:我要退回清单 项目对象作为 IEnumerable。如果项目财产在 我的 DTO 是 List、IList、Collection?

    • IEnumerable&lt;T&gt;实现IEnumerable接口方法改进 可以迭代的集合。
    • ICollection&lt;T&gt; 继承了 IEnumerable 和 IEnumerable 接口。
    • IList 继承了 IEnumerable 和 ICollection 接口。
    • List 是一个类,它不仅实现了它们的接口,而且 扩展更多方法。

    因此,将 Project 对象列表作为 IEnumerable 返回是不正确的,但可以将其返回为 List, IList, ICollection

    尝试如下更改您的代码:

    public List<T> GetAll()
    

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 2023-01-13
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2022-07-06
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多