Skip to main content

Dapper & Micro-ORMs

When to Use Dapper

  • Complex queries
  • Performance-critical operations
  • Stored procedures
  • Reporting queries

Basic Usage

using Dapper;

var products = await connection.QueryAsync<Product>(
"SELECT * FROM Products WHERE Price > @MinPrice",
new { MinPrice = 100 });

Multi-Mapping

var orders = await connection.QueryAsync<Order, Customer, Order>(
"SELECT * FROM Orders o INNER JOIN Customers c ON o.CustomerId = c.Id",
(order, customer) =>
{
order.Customer = customer;
return order;
},
splitOn: "Id");

Dapper vs EF Core

FeatureDapperEF Core
PerformanceFasterGood
FlexibilityHighMedium
Learning CurveLowHigher
Change TrackingNoYes
MigrationsNoYes

Connection Pooling

// Automatic in ASP.NET Core
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));

Response Compression

builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
});

app.UseResponseCompression();

Async/Await Best Practices

// ✅ Good
public async Task<List<Product>> GetProductsAsync()
{
return await _context.Products.ToListAsync();
}

// ❌ Bad - Blocking
public List<Product> GetProducts()
{
return _context.Products.ToList();
}

Use DTOs

// Don't return entities directly
public record ProductDto(int Id, string Name, decimal Price);