简体   繁体   中英

Cannot implicitly convert type 'IEnumerable<T>' to 'ActionResult<IEnumerable<T>>'

I am trying to get a list of entries from database. But I am getting an error.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<models.DbModels.GrantProgram>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<models.DbModels.GrantProgram>>' [API]

Please help me. How can I solve this?

Controller.cs

public async Task<ActionResult<IEnumerable<GrantProgram>>> GetGrants()
{
  //This is where the error is showing. 
  return await _grants.GetGrants(); 
}

Business layer

IGrants.cs

Task<IEnumerable<GrantProgram>> GetGrants(); 

Grants.cs

public async Task<IEnumerable<GrantProgram>> GetGrants()
{
    return await _grantRepository.GetGrants(); 
}

Data access layer

IGrantsRepository.cs

Task<IEnumerable<GrantProgram>> GetGrants(); 

GrantsRepository.cs

public async Task<IEnumerable<GrantProgram>> GetGrants()
{
    return await _context.GrantProgram.ToListAsync();
}

since you are using ActionResult consider to use this

public async Task<ActionResult<IEnumerable<GrantProgram>>> GetGrants()
{
 
  return Ok ( await _grants.GetGrants() ); 
}

I suspect the code you want is something like

return new ActionResult<IEnumerable<GrantProgram>>(await _grants.GetGrants());

Why does your existing code not work? Because (as per the docs ):

C# doesn't support implicit cast operators on interfaces.

It suggests:

Consequently, conversion of the interface to a concrete type is necessary to use ActionResult.

which is not strictly speaking true. It is an option , yes (eg call ToList ), but it isn't necessary . Another option (as I show) is to new up ActionResult yourself rather than rely on the implicit conversion).

Other reading:

According to the Docs ( Controller action return types in ASP.NET Core web API , published in February 2022), consider only using ActionResult as the return type if your method could return different ActionResults. Since this example only has one return path, you could instead use simpler code that defines a specific type as the return value. Here is what your code would look like with this change:

Controller.cs

public async Task<IEnumerable<GrantProgram>> GetGrants()
{
  //This is where the error is showing. 
  return await _grants.GetGrants(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM