Home > Mobile >  How to make a complicated LINQ query to DB Asynchronous?
How to make a complicated LINQ query to DB Asynchronous?

Time:12-14

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?

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

CodePudding user response:

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.

  • Related