-1

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();
1

1 Answer 1

1

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();
1
  • 2
    It looks like they're trying to chain on an optional Where condition which ideally would be processed by the queryable too, usually, so the ToListAsync() should probably be in the return line instead. Commented Oct 28 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.