ASP.NET-Core-Template icon indicating copy to clipboard operation
ASP.NET-Core-Template copied to clipboard

How to apply the .ToListAsync();?

Open MiBuena opened this issue 3 years ago • 5 comments

In asynchronous programming there is a very useful async method: ToListAsync(); However, it comes from EntityFramework. So basically if we use the template here and call .All(); method in the Service and after that call .ToListAsync() in the service - then we will create a dependency between the Service and EF.

Perhaps I should add a wrapper method for this in the generic repository like I have done it here:

Or maybe there is a better way? Let me know your thoughts!

https://github.com/MiBuena/ListGeneratorAsync/blob/19093c731337d7b1b2a91963e047873142f4d9de/ListGeneration.Data/Repositories/EfRepository.cs#L30

MiBuena avatar Dec 08 '21 08:12 MiBuena

Yes, you are absolutely right. ToListAsync is missing in the current EfRepository implementation. Anyway you can use it after calling the .All() method.

NikolayIT avatar Dec 08 '21 14:12 NikolayIT

Hello, Niki! Could you please clarify:

Shall I use it in the Service like this: _itemsRepository.All().ToListAsync(); ?

Or leave it as a wrapper method in the repository and calling it like this?

MiBuena avatar Dec 08 '21 15:12 MiBuena

I suggest you using it like await repo.All().ToListAsync() in case you want all records and of course await repo.All().Where(x => ...).ToListAsync() in case you want some filtering.

NikolayIT avatar Dec 08 '21 15:12 NikolayIT

Ok, but if I put it like this, 2 problems arrise:

  1. I will have to add the following using the Service: using Microsoft.EntityFrameworkCore; .ToListAsync() requires it. This I believe creates a dependency between the Service and EF?

  2. After that I get an Exception in the Unit test - "The source IQueryable doesn't implement IAsyncEnumerable<ListGenerator.Shared.Dtos.ItemNameDto>. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations."

MiBuena avatar Dec 08 '21 15:12 MiBuena