CodeNewbie
CodeNewbie

Reputation: 19

How can I have an async response with an IQueryable?

I get the warning message

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

The code that produces this warning is

app.MapGet("/questionsByCategory", async (Context dbContext, int categoryId, bool inTest) =>
        {
            IQueryable<Questions> result = dbContext.Questions
                .AsNoTracking()
                .Where(x => x.CategoryId == categoryId)
                .Include(x => x.Answers)
                .AsQueryable();

            if (inTest)
                result.Where(x => x.InTest == true);

            return Results.Ok(result);
        })
        .WithName("questionsByCategory")
        .WithOpenApi();

Upvotes: -1

Views: 171

Answers (1)

Bogdan Shahnitsky
Bogdan Shahnitsky

Reputation: 792

Updated according to Damien_The_Unbeliever's comment:

Add the .ToListAsync() call before returning the result. Here's an updated code snippet:

app.MapGet("/questionsByCategory", async (Context dbContext, int categoryId, bool inTest) =>
        {
            IQueryable<Questions> query = dbContext.Questions
                .AsNoTracking()
                .Where(x => x.CategoryId == categoryId)
                .Include(x => x.Answers)
                .AsQueryable();

            if (inTest)
                query.Where(x => x.InTest == true);

            var result = await query.ToListAsync();
            return Results.Ok(result);
        })
        .WithName("questionsByCategory")
        .WithOpenApi();

Upvotes: 1

Related Questions