.Net Core Web API - How Do I Populate a DTO That Contains a Generic List

1.1k views Asked by At

My datamodel consists of a 1 to many relationship between an Employee table and a Projects table. I need my DTO to return an Employee object that contains a collection/list of Project objects. I am using a repository pattern to return data from the database. Question 1: How do I populate the List property of the DTO? Question 2: Is my approach a correct one? Question 3: I am returning the list of Project objects as an IEnumerable. Should the Projects property in my DTO be a List, IList, Collection? Here is my code. Thank you in advance.

//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);
}
1

There are 1 answers

0
LouraQ On

Question 1: How do I populate the List property of the DTO? Question 2: Is my approach a correct one? Question 3: I am returning the list of Project objects as an IEnumerable. Should the Projects property in my DTO be a List, IList, Collection?

  • IEnumerable<T> implements the IEnumerable interface method to improve the collection that can be iterated.
  • ICollection<T> inherits both IEnumerable and IEnumerable interfaces.
  • IList inherits the IEnumerable and ICollection interfaces.
  • List is a class, which not only implements their interface, but also extends more methods.

So, returning the list of Project objects as an IEnumerable is not correct, but it can be returned as List, IList, ICollection.

Try change your code as follow:

public List<T> GetAll()