I am running a query which loads pages of data for different tenants. Each tenant has its own database and the table has more than 500K records. I get this error from time to time and not always. It seems that it happens due to the connection not being disposed of properly but I am using the using
block. Here is my code what am I missing?
The query method
public async Task<DetailedPagedResultSet<ResultSet>> GetData(Guid userId, string role, int pageNumber, int pageSize)
{
var query = $@"";
var parameters = new DynamicParameters();
using var connection = _dapperContext.GetConnectionForCurrentTenant();
await connection.OpenAsync();
var result = await connection.QueryPagedAsync<ResultSet>(query, pageSize, pageNumber, parameters);
return result;
}
The pager extension method
public static async Task<DetailedPagedResultSet<T>> QueryPagedAsync<T>(this IDbConnection connection, string baseQuery, int pageSize, int currentPageNumber, DynamicParameters parameters)
where T : PagedResultSet
{
var pagedQuery = new StringBuilder();
pagedQuery.Append("SELECT tm.*, COUNT(*) OVER () AS RowCount FROM (");
pagedQuery.Append(baseQuery);
pagedQuery.Append(@") AS tm LIMIT @pageSize OFFSET @offset;");
var offset = (currentPageNumber - 1) * pageSize;
parameters.Add("@pageSize", pageSize);
parameters.Add("@currentPage", currentPageNumber);
parameters.Add("@offset", offset);
var data = await connection.QueryAsync<T>(pagedQuery.ToString(), parameters);
var totalPages = 0;
var totalRows = 0;
if (data.IsNotEmpty())
{
totalRows = data.First().RowCount;
totalPages = (int)Math.Ceiling(totalRows / (double)pageSize);
}
return new DetailedPagedResultSet<T>()
{
PageCount = totalPages,
RowCount = totalRows,
PageCurrent = currentPageNumber,
PageSize = pageSize,
Results = data
};
}