Dapper SqlBuilder with multiple results

dapper

Use Dapper SQL builder to create complex queries with pagination


using SqlConnection connection = new(_configuration.GetConnectionString("Default"));

SqlBuilder builder = new();
builder.Select("Id");
builder.Select("UserName");
builder.Select("ExpireDate");
builder.Select("IdNumber");

DynamicParameters parameters = new();
parameters.Add("@Username", $"{searchUser.UserName}%", DbType.String, ParameterDirection.Input);
parameters.Add("@Offset", searchUser.Offset);
parameters.Add("@Limit", searchUser.Limit);

builder.Where("UserName LIKE @Username", parameters);

var builderTemplate = builder.AddTemplate(@"
    SELECT /**select**/ 
    FROM Users /**where**/ 
    ORDER BY Id
    OFFSET @Offset ROWS
    FETCH NEXT @Limit ROWS ONLY;
                   
    SELECT COUNT(*) FROM Users /**where**/
");

var queryResult = await connection.QueryMultipleAsync(builderTemplate.RawSql, builderTemplate.Parameters);

Users = (await queryResult.ReadAsync<CredentialUser>()).ToArray();
TotalUsers = await queryResult.ReadFirstAsync<int>();

Post a Comment

Previous Post Next Post