NTDLS.SqlServerDapperWrapper Usage
A simple Dapper-based interface to SQL Server with automatic cleanup and stored procedure detection.
NTDLS.SqlServerDapperWrapper
What it is. A thin, friendly layer over Dapper for SQL Server. Each call opens a connection, executes, then closes and disposes it - no connection bookkeeping on your part. It auto-detects whether the string you pass is a stored procedure name, inline T-SQL, or an embedded .sql resource file, and supports transactions through an Ephemeral block that keeps one connection alive for multiple steps.
When to reach for it. You want POCO-style Dapper access to SQL Server without managing SqlConnection lifetimes, and you like the idea of calling ExecuteScalar("MyProc") and having it just work. Skip it if you need long-lived connections or micro-managed pooling; use the underlying SqlServerManagedInstance directly in that case.
Getting started
Create a factory once, pointing at your server and database:
public static SqlServerManagedFactory MyConnection { get; } = new("localhost", "tempdb");
Then execute anything - a procedure, a query, or an embedded script file - with the same method:
// Stored procedure (auto-detected):
var procValue = MyConnection.ExecuteScalar<DateTime>("TestProc");
// Inline T-SQL:
var textValue = MyConnection.ExecuteScalar<DateTime>("SELECT GetDate()");
// Embedded .sql resource file:
var sqlValue = MyConnection.ExecuteScalar<DateTime>("TestSqlFile.sql");
Parameterized inserts take an anonymous object, and multi-step work happens inside Ephemeral, which holds a single open connection for the duration of the lambda:
for (int i = 0; i < 100; i++)
{
var param = new { Name = $"Name #{i}", Description = Guid.NewGuid().ToString() };
MyConnection.Execute("INSERT INTO Test (Name, Description) VALUES (@Name, @Description)", param);
}
MyConnection.Ephemeral(o =>
{
using var tx = o.BeginTransaction();
try
{
o.Execute("UPDATE Test SET Description = NULL WHERE Id > 50");
tx.Commit();
}
catch
{
tx.Rollback();
throw;
}
});
// Query into POCOs:
var results = MyConnection.Query<TestModel>("SELECT * FROM Test");
foreach (var result in results)
{
Console.WriteLine($"{result.Id} {result.Name}");
}
NuGet: NTDLS.SqlServerDapperWrapper