![](/img/trans.png)
[英]Cannot implicitly convert type of IEnumerable<T> to IEnumerable<T>
[英]Cannot implicitly convert type 'IEnumerable<T>' to 'ActionResult<IEnumerable<T>>'
我正在尝试从数据库中获取条目列表。 但是我收到一个错误。
无法将类型“System.Collections.Generic.IEnumerable<models.DbModels.GrantProgram>”隐式转换为“Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<models.DbModels.GrantProgram>>”[API]
请帮我。 我该如何解决这个问题?
Controller.cs
public async Task<ActionResult<IEnumerable<GrantProgram>>> GetGrants()
{
//This is where the error is showing.
return await _grants.GetGrants();
}
业务层
IGrants.cs
Task<IEnumerable<GrantProgram>> GetGrants();
Grants.cs
public async Task<IEnumerable<GrantProgram>> GetGrants()
{
return await _grantRepository.GetGrants();
}
数据访问层
IGrantsRepository.cs
Task<IEnumerable<GrantProgram>> GetGrants();
GrantsRepository.cs
public async Task<IEnumerable<GrantProgram>> GetGrants()
{
return await _context.GrantProgram.ToListAsync();
}
因为你正在使用 ActionResult 考虑使用这个
public async Task<ActionResult<IEnumerable<GrantProgram>>> GetGrants()
{
return Ok ( await _grants.GetGrants() );
}
我怀疑你想要的代码是这样的
return new ActionResult<IEnumerable<GrantProgram>>(await _grants.GetGrants());
为什么您现有的代码不起作用? 因为(根据文档):
C# 不支持接口上的隐式转换运算符。
它建议:
因此,必须将接口转换为具体类型才能使用 ActionResult。
严格来说这不是真的。 这是一个选项,是的(例如调用ToList
),但不是必需的。 另一种选择(如我所示)是自己new
ActionResult
而不是依赖隐式转换)。
其他阅读:
根据文档( Controller 动作返回类型 in ASP.NET Core web API,2022年 2 月发布),如果您的方法可以返回不同的 ActionResults,请考虑仅使用 ActionResult 作为返回类型。 由于此示例只有一个返回路径,因此您可以改用更简单的代码,将特定类型定义为返回值。 以下是您的代码经过此更改后的样子:
Controller.cs
public async Task<IEnumerable<GrantProgram>> GetGrants()
{
//This is where the error is showing.
return await _grants.GetGrants();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.