EF Core DbContext Where Async

c# entity-framework-core

Question

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.
1
0
3/24/2020 2:52:00 PM

Popular Answer

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.

0
3/24/2020 3:01:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow