Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SqlBuilder

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?

like image 610
idlackage Avatar asked Sep 25 '13 15:09

idlackage


2 Answers

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

like image 115
drizin Avatar answered Oct 12 '22 18:10

drizin


To this date, SqlBuilder has not made yet to any official package on Nuget. I got that installed by using the following package: Dapper.SqlBuilder. I really hope it becomes part of the official library.

Anyways, to your question, once the package is installed, you don't need to add any new "using" clause, as the SqlBuilder is inside the same Dapper namespace.

You can check the source code details in here: https://github.com/StackExchange/dapper-dot-net/blob/master/Dapper.SqlBuilder/SqlBuilder.cs

EDIT: The package can be found at: https://www.nuget.org/packages/Dapper.SqlBuilder/

like image 20
Fabricio Avatar answered Oct 12 '22 18:10

Fabricio