How to use SqlBuilder

This question appears in the dapper tutorial page, so I'm updating the answer.

In version 1.6, SqlBuilder is in the namespace Dapper. And it is included in the nuget package Dapper.SqlBuilder.

This is an example of how it works:

var builder = new SqlBuilder();
builder.Select("id_something");
builder.Select("MyCol");
builder.Select("OtherCol");
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@MyParam", 3, DbType.Int32, ParameterDirection.Input);
builder.Where("id_something < @MyParam", parameters);
// builder.Where("id_something < @MyParam", new { MyParam =3}); //this is other option for params.
builder.InnerJoin("OtherTable on OtherTable.id=MyTable.id");
//The /**something**/ are placeholders,
var builderTemplate = builder.AddTemplate("Select /**select**/ from MyTable /**innerjoin**/ /**where**/ ");
var result = connection.Query<MyClass>(builderTemplate.RawSql, builderTemplate.Parameters);

This is the Sql generated:

Select id_something , MyCol , OtherCol
 from MyTable 
INNER JOIN OtherTable on OtherTable.id=MyTable.id
 WHERE id_something < @MyParam

There's a library called DapperQueryBuilder which is an alternative to Dapper SqlBuilder, and the similar code from question above would be like this:

// using DapperQueryBuilder; ...

int myParam = 3;
var builder = cn.QueryBuilder();

builder.Select($"id_something");
builder.Select($"MyCol");
builder.Select($"OtherCol");
builder.From($"MyTable");
builder.From($"inner join OtherTable on OtherTable.id=MyTable.id");
builder.Where($"id_something < {myParam}");

var result = builder.Query<MyClass>();

Or even shorter if the only dynamic part is the filters:


var builder = cn.QueryBuilder($@""
    SELECT id_something, MyCol, OtherCol
    FROM MyTable
    inner join OtherTable on OtherTable.id=MyTable.id
    /**where**/
");

int myParam = 3;
builder.Where($"id_something < {myParam}");

var result = builder.Query<MyClass>();

Even though it looks like we're using unsafe interpolated strings, that's not true - the output is fully parametrized SQL (WHERE id_something < @p0) - and you don't have to manually manage the dictionary of parameters as you would do if using SqlBuilder.

Disclaimer: I'm the author of this library