How to use SqlBuilder

idlackage picture idlackage · Sep 25, 2013 · Viewed 14.7k times · Source

This SqlBuilder:

var builder = new SqlBuilder(); 
var sql = builder.AddTemplate( /*...

Intensely dumb question but, how do I use this? I know it's in Dapper.Contrib, but that using statement isn't enough. What references or other using statements do I need to add?

Answer

Carlos Cuevas picture Carlos Cuevas · Apr 5, 2019

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