简体   繁体   English

EF Core DbContext Where Async

[英]EF Core DbContext Where Async

I'm trying to execute a query that contains a WHERE as an Async function.我正在尝试执行包含 WHERE 作为异步函数的查询。 Just like using the FirstAsync action, but there's no WhereAsync so I was wondering if there is some workaround.就像使用FirstAsync操作一样,但没有WhereAsync所以我想知道是否有一些解决方法。

I have an ApplicationRepository object that has an GetEntitiesAsync function and I tried this:我有一个具有GetEntitiesAsync函数的ApplicationRepository对象,我试过这个:

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.

There is an ToListAsync method that can be called asynchronously to get the data.有一个ToListAsync方法可以异步调用以获取数据。

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 .获取数据需要大量时间,因此 async 不在Where方法上,而是在获取数据的方法上,如ToArrayAsyncFirstAsync

The Where clause doesn't actually do anything, it's deferred execution. Where子句实际上并没有做任何事情,它只是延迟执行。 You can just use FirstAsync , ToListAsync , or ToArrayAsync with Where .您可以只将FirstAsyncToListAsyncToArrayAsyncWhere ToArrayAsync使用。

In your code, you should remove the AsQueryable() part.在您的代码中,您应该删除AsQueryable()部分。 Without it, you should be OK:没有它,你应该没问题:

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

And yes, you should use an Expresion instead of Func .是的,您应该使用Expresion而不是Func It's possible the DbSet or DbContext doesn't offer an overload for Where that accepts Func . DbSetDbContext可能没有为接受Func Where提供重载。 That' pretty common, actually.实际上,这很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM