C#C
C#4y ago
Utsuhoagie

LINQ expression could not be translated after converting object

public static BugDTO ConvertToDTO(Bug bug) => new BugDTO
{
    Id = bug.Id,
    Description = bug.Description,
    IsFixed = bug.IsFixed
};

// GET: api/Bugs
//    api/Bugs?isFixed={true|false}
[HttpGet]
public async Task<ActionResult<IEnumerable<Bug /* BugDTO */>>> GetBugs([FromQuery] bool? isFixed)
{
    // var allBugDTO = _context.Bugs.Select(bug => ConvertToDTO(bug));
    var allBugDTO = _context.Bugs.Select(bug => bug);

    if (isFixed == null)
    {
        var allBugDTOList = await allBugDTO.ToListAsync();
        return allBugDTOList;
    }

    var filteredBugDTOList = await allBugDTO.Where(bug => bug.IsFixed == isFixed!).ToListAsync();
    return filteredBugDTOList;
}        


Why am I getting this error when I try to convert an object to another very similar object? This is in ASP.NET with Web API scaffolding, in my BugController.cs class. Bug and BugDTO are almost identical classes, except Bug has an extra property.
If I run the code below, it works just fine. But if I change the return type from ...<Bug>... with ...<BugDTO>..., and change the lambda expr in _context.Bugs.Select(...) to also convert the Bugs to BugDTOs, then the error in the screenshot happens.
I originally thought it was due to isFixed being nullable, but forgiving null doesn't change anything. The error message also shows my lambda expr as b => (bool?)BugsController... which could be a problem, but I don't know what. Both allBugDTOList and filteredBugDTOList are of type List<BugDTO> as well, assuming I made the DTO-related changes in my 2nd paragraph.
Any help's appreciated, I'm still very new to C#
unknown.png
Was this page helpful?