Reputation: 23
Though some answers are in this area, none answer my question. This function is a part of a Projects repository. Projects have a lot of items, but there are times when only the "Header" elements are needed from it. The Header is NOT stored separately, but has a different "API..Dto". (This has to get shipped back to the front-end)
public async Task<ActionResult<List<ProjectAPIHeaderDto>>> GetAllProjectHeaders()
{
var projects = await _context.Projects.ToListAsync(); // full project records
var records = _mapper.Map<List<ProjectAPIHeaderDto>>(projects); // only some fields from project
return records;
}
The problem is:
Cannot implicitly convert type 'System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.List<API.DTOs.ProjectAPIHeaderDto>>>' to 'System.Collections.Generic.List<API.DTOs.ProjectAPIHeaderDto>'
Similar code works perfectly in another function shown here:
public async Task<List<ProjectAPIDto>> GetAllProjects()
{
var projects = await _context.Projects.ToListAsync();
var records = _mapper.Map<List<ProjectAPIDto>>(projects);
return records;
}
ProjectAPIDto has all fields from the projects while ProjectAPIHeaderDto has a few of the project fields.
This link is hover over var records and shows it is List. enter image description here
this is ProjectAPIHeaderDto:
using System.ComponentModel.DataAnnotations;
namespace API.DTOs
{
public class ProjectAPIHeaderDto
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
}
}
Looking again at the error message: System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.ActionResult I've never seen this problem before anywhere.. is ActionResult the problem?
Thanks in advance for your help.
Upvotes: 2
Views: 709
Reputation: 3286
Try to use Task<IActionResult>
instead and wrap your result in an Ok(...)
(or whatever is needed in your response).
public async Task<IActionResult> GetAllProjectHeaders()
{
var projects = await _context.Projects.ToListAsync(); // full project records
var records = _mapper.Map<List<ProjectAPIHeaderDto>>(projects); // only some fields from project
return Ok(records);
}
Here you can find a good comparison of the three options.
Note: If your are using any kind of client generation tool (Nswag, Swashbuckle, ...) you need to specify a response type attribute because the
IActionResult
has noT
Upvotes: 0