Asp.net core webapi .NET核心API视图模型返回
我正在尝试运行一个查询,该查询只返回模型和相关实体的select字段。我得到一个错误:Asp.net core webapi .NET核心API视图模型返回,asp.net-core-webapi,Asp.net Core Webapi,我正在尝试运行一个查询,该查询只返回模型和相关实体的select字段。我得到一个错误: Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: int TeamId, string N
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
严重性代码描述项目文件行抑制状态
错误CS0029无法隐式转换类型
“System.Collections.Generic.List”到“Microsoft.AspNetCore.Mvc.ActionResult”AppName C:..\Controllers\TeamController.cs 64活动
我做错了什么
[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; }
}
[HttpGet(“{id}”)]
公共异步任务列表(int-id)
{
var team=wait_context.Teams
.其中(c=>c.TeamId==id)
.选择(c=>new
{
c、 TeamId,
c、 团队名称
})
.ToListAsync();
如果(团队==null)
{
返回NotFound();
}
返回队;
}
类TeamViewModel
{
[必需]
public int TeamId{get;set;}
[必需]
公共字符串TeamName{get;set;}
}
您正在选择一个匿名类型,并试图将其作为具体的TeamViewModel
类型返回
假设TeamViewModel
是预期的类型,并且它是用原始问题中尝试的属性定义的,那么应该重构操作
[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;
}
[HttpGet(“{id:int}”)]
公共异步任务列表(int-id){
var team=wait_context.Teams
.其中(c=>c.TeamId==id)
.选择(c=>new TeamViewModel{//谢谢!这解决了我的问题,我能够获得我想要的数据,但是,我也从我的团队实体中获取所有字段。我的select仅包括TeamId和TeamName这一事实不应该意味着我只获取这些字段吗?您将从上下文中获取所有内容,但投影仅访问两个属性。您确定吗rmine从控制器操作返回多少。这就是为什么通常建议创建视图模型而不发送实体的原因。我明白了。这就是我试图通过在视图模型上创建投影来完成的。我将使用它。