Jossean Yamil
Jossean Yamil

Reputation: 1070

EF Core DbContext Where Async

I'm trying to execute a query that contains a WHERE as an Async function. Just like using the FirstAsync action, but there's no WhereAsync so I was wondering if there is some workaround.

I have an ApplicationRepository object that has an GetEntitiesAsync function and I tried this:

public async Task<IEnumerable<TEntity>> GetEntitiesAsync<TEntity>(Func<TEntity, bool> selector) where TEntity : class => 
            await _context.Set<TEntity>().Where(selector).AsQueryable().ToArrayAsync();

However, this line of code throws an exception:

System.InvalidOperationException: The source IQueryable doesn't implement IAsyncEnumerable<OneStopApp.Models.CustomForm>. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

Upvotes: 3

Views: 8320

Answers (2)

igg
igg

Reputation: 2250

The Where clause doesn't actually do anything, it's deferred execution. You can just use FirstAsync, ToListAsync, or ToArrayAsync with Where.

In your code, you should remove the AsQueryable() part. Without it, you should be OK:

await _context.Set<TEntity>().Where(selector).ToArrayAsync();

And yes, you should use an Expresion instead of Func. It's possible the DbSet or DbContext doesn't offer an overload for Where that accepts Func. That' pretty common, actually.

Upvotes: 0

Martin Staufcik
Martin Staufcik

Reputation: 9490

There is an ToListAsync method that can be called asynchronously to get the data.

var list = await db.Accounts.Where(x => true).ToListAsync();

Fetching the data takes the bulk of time, therefore async is not on the Where method, but it is on methods that get the data like ToArrayAsync or FirstAsync.

Upvotes: 7

Related Questions