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.
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.