For an admin page I need to provide several tables' total counts.
This is my current code:
[HttpGet("stats")]
public async Task<StatsVM> GetStats()
{
var result = new StatsVM();
result.TotalTable1 = await dbContext.Table1.CountAsync(...);
result.TotalTable2 = await dbContext.Table2.CountAsync(...);
result.TotalTable3 = await dbContext.Table3.CountAsync(...);
result.TotalTable4 = await dbContext.Table4.CountAsync(...);
return result;
}
To my understandings this will result in four DB trips (and there will be more in future). Is there a way to do it in one DB trip?
Update:
Will the following code result in one DB trip? The query on Table1
could be any non-empty table.
var result = await dbContext.Table1
.AsNoTracking()
.Select(c => new StatsVM
{
TotalTable1 = dbContext.Table1.Count(),
TotalTable2 = dbContext.Table2.Count(),
//...
})
.FirstAsync();