Skip to content

Module 3: Dapper Micro-ORM (The Shortcut)

📚 Module 3: Dapper Micro-ORM

Course ID: DOTNET-202
Subject: The SQL Shortcut

Entity Framework (Module 1) is a “Heavyweight” ORM. It does everything for you. Dapper is a “Micro-ORM.” It only does one thing: Map SQL results to C# objects as fast as possible.


🏗️ Step 1: The “Overhead” Problem

Imagine you are a world-class driver.

  • Entity Framework: Like a self-driving car. You tell it where to go, and it handles the steering, braking, and navigation. (Easy, but sometimes takes a slower route).
  • Dapper: Like a manual race car. YOU write the SQL (The steering). Dapper just ensures the fuel gets to the engine (Mapping the data).

🏗️ Step 2: When to use Dapper?

  1. Massive Scale: When you are reading millions of rows and every millisecond counts.
  2. Complex SQL: When your DBA has written a 200-line SQL query that is too complex for EF Core to understand.

🧪 Step 3: Python Practice (C# vs. SQL)

In Dapper, you write real SQL inside your C# strings. It’s very similar to using a raw cursor in Python’s psycopg2 or sqlite3.

// 1. Write raw SQL
string sql = "SELECT * FROM Products WHERE Price > @MaxPrice";

// 2. Run it and map to a list of objects automatically
var products = connection.Query<Product>(sql, new { MaxPrice = 100 });

🥅 Module 3 Review

  1. Dapper: A tiny, fast tool for raw SQL.
  2. Mapping: Turning table rows into C# objects.
  3. Performance: The fastest ORM in the .NET ecosystem.

Code example

public enum TargetDb
{
    ServiceRequest,
    Billing,
    Analytics
}

public enum TargetClient
{
    SqlServer,
    Postgres,
}

public interface IConnectionFactory
{
    public IDbConnection CreateConnection(TargetDb targetDb, TargetClient targetClient);
}

public class ConnectionFactory(IConfiguration configuration) : IConnectionFactory
{
    public IDbConnection CreateConnection(TargetDb targetDb, TargetClient targetClient)
    {
        var connectionString = configuration.GetConnectionString($"{targetDb}ConnectionString")
                                ?? throw new InvalidOperationException(
                                    $"Connection string for {targetDb} not found.");
        return targetClient switch
        {
            TargetClient.Postgres => new NpgsqlConnection(connectionString),
            TargetClient.SqlServer => new SqlConnection(connectionString),
            _ => throw new ArgumentOutOfRangeException(nameof(targetClient), targetClient,
                "Unsupported database provider.")
        };
    }
}

appsetting.json

{
  "ConnectionStrings": {
    "ServiceRequestConnectionString": "Server=mySqlServer;Database=ServiceRequests;...",
    "BillingConnectionString": "Host=myPostgresServer;Database=Billing;...",
    "AnalyticsConnectionString": "Data Source=myOracleServer;User Id=analytics;..."
  }
}