简体   繁体   中英

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;
    }

Here is the repo .

I build up the query and materialize it later on. When I materialize it - I use ToListAsync(); But I am wondering can this part - ".Select(m => (int?)m.Quantity).FirstOrDefault()," also be made async in some way?

PS Select returns an IEnumerable not IQueryable so we can not use ".FirstOrDefaultAsync()" right away.

When you execute a SQL-based Linq (like EF) query, the entire query is converted to SQL and then executed. In your example, the FirstOrDefault just tells the query generator how to formulate the 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. There is no need to try and convert the inner queries to async as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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