2
votes

I'm new to .NET Core, and I'm reading this doc https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.1

From there I'm practicing - I write this logic:

public async Task<ActionResult<List<DashBoar>>> GetAllAsync()
{
    var x = _Repo.GetPetsAsync();
    return await x.ToList();
}

But I'm getting an error.

My repo class is

public IEnumerable<DashBoar> GetPetsAsync()
{
    var x = from n in _context.DashBoar
            select n;
    return  x.ToList();
}
1
_Repo.GetPetsAsync() is the asynchronous operation, not x.ToList() - Camilo Terevinto
I think you must use ToListAsync(). - Llazar
I could tell you what to do, but you won't learn anything out of it. Just keep reading the tutorial because your code is far from what the tutorial shows - Camilo Terevinto
You Must NOT Capitalize Each And Every Single Word in the English language .... - marc_s
The reason why the compiler is complaining here is that you're awaiting the result of calling ToList, basically it looks like this: await (x.ToList());. Instead you could write it like this: (await x).ToList();. However, the answer provided by Asela is far more expressive. - Lasse V. Karlsen

1 Answers

5
votes

You should first understand what asynchronous programming is and the co-relation of await, async and Task.

Asynchronous programming is used to improve the application performance and enhance the responsiveness. Refer the links at the bottom to get an understanding.

First let's address your problem. Make your repo class return type as a Tak

public async Task<IEnumerable<DashBoar>> GetPetsAsync()
{
     var x = await (from n in _context.DashBoar
             select n).ToListAsync();

     return x;
}

Then call the repo method from GetAllAsync() method as below

public async Task<ActionResult<List<DashBoar>>> GetAllAsync()
{
     var x = await _Repo.GetPetsAsync();
     return x;
}

Please go through the below links To get a better understanding of asynchronous programming.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/ https://www.youtube.com/watch?v=C5VhaxQWcpE

https://www.dotnetperls.com/async

Good luck..!