1

I have some code

            var battleDetails = await _dbContext.BattleDetails
                .Select(x => new 
                { 
                    x.Hero, 
                    BattlesCount = _dbContext.BattleDetails
                        .Count(y => y.Hero == x.Hero)

                })
                .ToListAsync();

And I want to use CountAsync method instead of Count, but when I try to do this I am getting an error.

I have tried multiple ways, FE

                .Select(async x => new 
                { 
                    x.Hero, 
                    BattlesCount = await _dbContext.BattleDetails
                        .CountAsync(y => y.Hero == x.Hero)
                })

What should I do to make it async?

user12398280
  • 117
  • 1
  • 8
  • 1
    Would you mind adding the error you are receving? – Marco May 18 '22 at 08:56
  • And format that code properly. – Fildor May 18 '22 at 08:56
  • 1
    You have already made the entire query async. What are you trying to achieve by making the inner parts separately async, apart from messing with the EF's ability to translate the entire thing to SQL? – GSerg May 18 '22 at 08:57
  • 3
    EF doesn't support embedding async operations in the query, and you don't need to either. The entire query is forwarded to the database server, and there sync vs. async is not a thing. Only the outer call matters. – Jeroen Mostert May 18 '22 at 08:58
  • What is the goal of the query? Do you want to have several rows for a hero or just on row for each hero with the respective count of battles? – Markus May 18 '22 at 09:02
  • 1
    Does this answer your question? [Using async / await inside .Select lambda](https://stackoverflow.com/questions/39518163/using-async-await-inside-select-lambda) – 41686d6564 stands w. Palestine May 18 '22 at 09:03
  • @JeroenMostert so you are saying both ways with `Count` and `CountAsync` will be executed in the same way? – user12398280 May 18 '22 at 09:13
  • 3
    No -- I'm saying you can't use `.CountAsync()` in the inner query at all in this case, but it doesn't matter. It will end up as one query doing joins on the database end, and (if your DB engine is any good) done with asynchronous I/O and even in parallel if your data is big enough. The `.ToListAsync()` at the end is what makes the whole thing async on the client end. Don't mistake the code inside the `Select` for code that is executed as C# code -- it ends up as an expression tree and is translated to SQL. – Jeroen Mostert May 18 '22 at 09:18

0 Answers0