A simple and performant SQL builder for Dapper, using string interpolation and a fluent API to build safe, static, and dynamic SQL queries.
Install via the .NET Core command line interface
dotnet add package Dapper.SimpleSqlBuilderOr via the NuGet Package Manager Console
Install-Package Dapper.SimpleSqlBuilderFor information on installing other available packages, refer to the Packages section in the documentation.
The library provides two builders for building SQL queries, which can be created via the static SimpleBuilder class.
Builder- for building static, dynamic, and complex SQL queries.Fluent Builder- for building SQL queries using a fluent API.
The library also provides an alternative to static classes via Dependency Injection.
using Dapper.SimpleSqlBuilder;
var userTypeId = 4;
var role = "Admin";
var builder = SimpleBuilder.Create($@"
SELECT * FROM User
WHERE UserTypeId = {userTypeId} AND Role = {role}");Note
The concern you might have here is the issue of SQL injection, however this is mitigated by the library as the SQL statement is converted to this.
SELECT * FROM User
WHERE UserTypeId = @p0 AND Role = @p1And all values passed into the interpolated string are taken out and replaced with parameter placeholders. The parameter values are put into Dapper's DynamicParameters collection.
To execute the query with Dapper is as simple as this:
var users = dbConnection.Query<User>(builder.Sql, builder.Parameters);To learn more about the Builder, refer to the Builder section in the documentation.
using Dapper.SimpleSqlBuilder;
var userTypeId = 4;
var roles = new[] { "Admin", "User" };
var builder = SimpleBuilder.CreateFluent()
.Select($"*")
.From($"User")
.Where($"UserTypeId = {userTypeId}")
.Where($"Role IN {roles}");
// Execute the query with Dapper
var users = dbConnection.Query<User>(builder.Sql, builder.Parameters);The generated SQL will be:
SELECT *
FROM User
WHERE UserTypeId = @p0 AND Role IN @pc1_Note
When the query is executed, Dapper will expand the parameter pc1_ into individual parameters (pc1_1, pc1_2, etc.) for each value in the collection.
To learn more about the Fluent Builder, refer to the Fluent Builder section in the documentation.
For advanced configuration options including parameter naming conventions, prefixes, and other settings, visit the Builder Settings section in the documentation.
Explore the complete Documentation to learn more about the library's features and usage.
If you like the library, use it, share it, and give it a ⭐️. For any suggestions, feature requests, or issues feel free to create an issue to help improve the library.
Refer to the Contributing guide for more details.
This project is licensed under the MIT License. See the LICENSE file for details.
Refer to the Acknowledgements page for more details.