[英]How to make a complicated LINQ query to DB Asynchronous?
I have a synchronous project which I am currently working to make asynchronous.我有一个同步项目,我目前正在努力使其异步。
I have the following query.我有以下查询。 It aims to take data for a particular purchase item and then take the last date the item was purchased and in what quantity it was purchased.
它旨在获取特定购买项目的数据,然后获取该项目的最后购买日期和购买数量。
private IQueryable<ItemOverviewDto> GetBaseQuery(string userId)
{
var query = this.Context.Items
.Where(x => x.UserId == userId)
.Select(x => new ItemOverviewDto()
{
Id = x.Id,
Name = x.Name,
ReplenishmentPeriod = x.ReplenishmentPeriod,
NextReplenishmentDate = x.NextReplenishmentDate,
LastReplenishmentDate = x.Purchases
.OrderByDescending(y => y.ReplenishmentDate)
.Select(m => (DateTime?)m.ReplenishmentDate)
.FirstOrDefault(),
LastReplenishmentQuantity = x.Purchases
.OrderByDescending(y => y.ReplenishmentDate)
.Select(m => (int?)m.Quantity)
.FirstOrDefault(),
});
return query;
}
I build up the query and materialize it later on.我建立了查询并稍后实现它。 When I materialize it - I use ToListAsync();
当我实现它时 - 我使用 ToListAsync(); But I am wondering can this part - ".Select(m => (int?)m.Quantity).FirstOrDefault()," also be made async in some way?
但我想知道这部分 - “.Select(m => (int?)m.Quantity).FirstOrDefault()”也可以以某种方式异步吗?
PS Select returns an IEnumerable not IQueryable so we can not use ".FirstOrDefaultAsync()" right away. PS Select 返回 IEnumerable 而不是 IQueryable,因此我们不能立即使用“.FirstOrDefaultAsync()”。
When you execute a SQL-based Linq (like EF) query, the entire query is converted to SQL and then executed.当您执行基于 SQL 的 Linq(类似 EF)查询时,整个查询将转换为 SQL 然后执行。 In your example, the
FirstOrDefault
just tells the query generator how to formulate the SQL.在您的示例中,
FirstOrDefault
只是告诉查询生成器如何制定 SQL。 It is not running a separate query inside the "main" query.它没有在“主”查询中运行单独的查询。
So when you call ToListAsync
, the entire query is converted to SQL and executed asynchronously.因此,当您调用
ToListAsync
时,整个查询将转换为 SQL 并异步执行。 There is no need to try and convert the inner queries to async as well.也无需尝试将内部查询转换为异步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.