Dapper Deploy & Usage Guide
A comprehensive guide for installing, building, and deploying applications using Dapper, the simple object mapper for .NET.
Prerequisites
- .NET SDK: 6.0 or later (8.0 recommended)
- Database: SQL Server (LocalDB/Express/Full), PostgreSQL, MySQL, or SQLite with ADO.NET provider
- IDE: Visual Studio 2022, JetBrains Rider, or VS Code with C# Dev Kit
- Git: For cloning the repository
Optional for benchmarks:
- SQL Server LocalDB or a running SQL Server instance (connection string required in
ConnectionStringsconfig)
Installation
Using NuGet (Recommended)
Add Dapper to your project:
# Core library
dotnet add package Dapper
# Optional extensions
dotnet add package Dapper.Contrib # CRUD extensions
dotnet add package Dapper.Rainbow # Micro-ORM table abstraction
Building from Source
Clone and build the repository:
git clone https://github.com/DapperLib/Dapper.git
cd Dapper
# Restore dependencies
dotnet restore
# Build the solution
dotnet build
Configuration
Connection Strings
Configure your database connection in appsettings.json (for ASP.NET Core) or environment variables:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDatabase;Trusted_Connection=True;TrustServerCertificate=True"
}
}
Or via environment variable:
export ConnectionStrings__DefaultConnection="Server=localhost;Database=MyDatabase;User Id=sa;Password=YourPassword;"
Database Provider Setup
Install the appropriate ADO.NET provider:
# SQL Server (modern)
dotnet add package Microsoft.Data.SqlClient
# PostgreSQL
dotnet add package Npgsql
# MySQL
dotnet add package MySql.Data
Build & Run
Build the Solution
# Debug build
dotnet build
# Release build
dotnet build -c Release
Running Tests
Execute the test suite (requires LocalDB or configured SQL Server):
# Run all tests
dotnet test
# Run with specific framework
dotnet test --framework net8.0
# Run with verbosity
dotnet test --verbosity normal
Running Benchmarks
The performance comparison tests (comparing Dapper to Entity Framework, NHibernate, etc.):
cd benchmarks/Dapper.Tests.Performance
# Run benchmarks
dotnet run -c Release
# Or specify a filter
dotnet run -c Release -- --filter *Dapper*
Note: Benchmarks require a valid connection string in LegacyTests.cs or via configuration. The benchmark project references multiple ORMs including:
- Entity Framework Core
- NHibernate
- ServiceStack.OrmLite
- Massive
Development Usage
Basic usage patterns based on the source implementation:
Query with DynamicParameters (Dapper/DynamicParameters.cs):
using var connection = new SqlConnection(connectionString);
var parameters = new DynamicParameters();
parameters.Add("Id", 1);
parameters.AddDynamicParams(new { Name = "Test" });
var result = connection.Query<MyEntity>("SELECT * FROM Table WHERE Id = @Id", parameters);
Multiple Result Sets with GridReader (Dapper/SqlMapper.GridReader.cs):
using var grid = connection.QueryMultiple("SELECT * FROM Table1; SELECT * FROM Table2");
var first = grid.Read<Table1>();
var second = grid.Read<Table2>();
Table Abstraction with Rainbow (Dapper.Rainbow/Database.cs):
public class MyDatabase : Database<MyDatabase>
{
public Table<Product, int> Products { get; set; }
}
using var db = MyDatabase.Init(connection);
var product = db.Products.Get(1); // Assumes Id column exists
Deployment
Deploying Applications Using Dapper
Since Dapper is a library, deployment involves publishing the host application:
# Publish for production
dotnet publish -c Release -o ./publish
# Docker containerization
docker build -t myapp .
docker run -e ConnectionStrings__DefaultConnection="..." myapp
CI/CD Pipeline (GitHub Actions Example)
name: Build and Test
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: '8.0.x'
- name: Restore
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
env:
ConnectionStrings__DefaultConnection: "Server=localhost;Database=DapperTest;User=sa;Password=TestPassword123;"
NuGet Package Creation
To package Dapper for redistribution:
# Create NuGet package
dotnet pack -c Release
# Push to NuGet (requires API key)
dotnet nuget push ./bin/Release/Dapper.*.nupkg --api-key $NUGET_API_KEY --source https://api.nuget.org/v3/index.json
Troubleshooting
Connection Issues
Error: "A network-related or instance-specific error occurred..."
- Solution: Verify SQL Server is running and TCP/IP is enabled
- Check firewall settings for port 1433 (SQL Server) or 5432 (PostgreSQL)
- Ensure
TrustServerCertificate=Truefor local development with SQL Server
Parameter Mapping Issues
Error: "Parameter '@ParamName' not found"
- Solution: Use
DynamicParametersclass for complex scenarios - Check parameter names match SQL exactly (case-sensitive in some providers)
- Ensure
AddDynamicParamsis called before query execution
Async Deadlocks
Symptom: Application hangs on async queries
- Solution: Always use
awaitwith async Dapper methods (QueryAsync,ExecuteAsync) - Avoid
.Resultor.Wait()on async methods in UI or ASP.NET contexts - Use
ConfigureAwait(false)in library code:var result = await connection.QueryAsync<Table1>(sql).ConfigureAwait(false);
Rainbow Table Name Resolution
Error: "Invalid object name 'Table'"
- Solution: Ensure your POCO class name matches the database table name, or override via
Table<T>constructor - Verify
DetermineTableName<T>implementation in yourDatabase<T>subclass
Performance Benchmark Failures
Error: Benchmarks fail with connection timeout
- Solution: Ensure SQL Server LocalDB is installed or update connection string in
LegacyTests.cs - Increase command timeout in test setup:
command.CommandTimeout = 120
Missing Provider Errors
Error: "Unable to find the requested .NET Framework Data Provider"
- Solution: Install the specific ADO.NET provider package (e.g.,
Microsoft.Data.SqlClientfor SQL Server) - Register the provider in
app.configif using .NET Framework legacy projects