I am trying to run a query that returns only select fields off of my model and related entities. I get an error:
Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly convert type
'System.Collections.Generic.List<<anonymous type: int TeamId, string Name>>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<ApplicationCore.Entities.TeamViewModel>>' AppName C:....\Controllers\TeamController.cs 64 Active
What am I doing wrong?
[HttpGet("{id}")]
public async Task<ActionResult<IEnumerable<TeamViewModel>>> List(int id)
{
var team = await _context.Teams
.Where(c => c.TeamId == id)
.Select(c => new
{
c.TeamId,
c.Team.Name
})
.ToListAsync();
if (team == null)
{
return NotFound();
}
return team;
}
class TeamViewModel
{
[Required]
public int TeamId { get; set; }
[Required]
public string TeamName { get; set; }
}
You are selecting an anonymous type and trying to return it as a concrete TeamViewModel
type.
Assuming TeamViewModel
was the intended type and that it is defined with the properties attempted in the original question, the action should be refactored..
[HttpGet("{id:int}")]
public async Task<ActionResult<IEnumerable<TeamViewModel>>> List(int id) {
var team = await _context.Teams
.Where(c => c.TeamId == id)
.Select(c => new TeamViewModel { //<--
TeamId = c.TeamId,
TeamName = c.Team.Name
})
.ToListAsync();
if (team.Count == 0) {
return NotFound();
}
return team;
}
Note your query wont return null so no need to check for that.
If the list is empty then that should indicate that there are no records.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加