I am following this tutorial. I am new to C# and need some help!
I am trying to add a feature to the GetUsers function to be able to get a list of "Users" associated with a "Company" in the else statement. The return type should be of type List<UserDTO>
(which it is in the if statement).
However, the else statement returns a List<User>
. How do I tell the database query to return a List<UserDTO>
?
I get this build error: Cannot implicitly convert type 'System.Collections.Generic.List<TestProj.Models.User>' to'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<TestProj.Models.UserDTO>>'
[HttpGet]
public async Task<ActionResult<IEnumerable<UserDTO>>> GetUsers(int? companyId)
{
if(companyId == null)
{
return await _context.Users.Select(x => UserToDTO(x)).ToListAsync();
}
else
{
return await _context.Users
.Where(x => x.CompanyId == companyId)
.ToListAsync();
}
}
private static UserDTO UserToDTO(User user) =>
new UserDTO
{
UserId = user.UserId,
Name = user.Name,
Email = user.Email,
CompanyId = user.CompanyId
};
Thanks in advance! :)
CodePudding user response:
you can try to Select to the UserDTO
return await _context.Users
.Where(x => x.CompanyId == companyId)
.Select(x => new UserDTO
{
UserId = x.UserId,
Name = x.Name,
Email = x.Email,
CompanyId = x.CompanyId
}).ToList();