v1.31.0
guíaPatrón · 01_Estructura_Tecnicaenglishversión en español

Data Access Guide: Dapper vs ADO.NET

This guide helps you choose the best data access option for your project.

3 minlectura
574palabras
9secciones
2026-09-22última edición
1cambios

This guide helps you choose the best data access option for your project.

Scope note: this guide compares Dapper and ADO.NET. The ecosystem's code generator also supports EF Core, which is its default (database.accessMode). Which combinations exist is stated by x-support in the configuration schema, not here.


Quick comparison

TraitDapper (recommended)ADO.NET
PerformanceVery high (close to native)Maximum (native)
ProductivityHighLow
Learning curveEasyMedium
BoilerplateMinimalA lot
Automatic mappingYesBy hand
MaintainabilityExcellentMedium
CommunityVery activeStable
NuGet packageDapperMicrosoft.Data.SqlClient

When to use which

Good for:

  • New projects
  • RESTful APIs
  • When you need both performance and productivity
  • Teams that want to write less code
  • Projects with complex queries where you still want simplicity
  • Scaling while staying maintainable

Advantages:

// Simple, clean code
var users = await connection.QueryAsync<User>(
    "SELECT * FROM Users WHERE IsActive = @IsActive",
    new { IsActive = true }
);

// Automatic mapping to objects
// No extra configuration
// Easy to read and maintain

Use ADO.NET (specific cases only)

Good for:

  • Absolute control over performance (the difference is < 5% versus Dapper)
  • Streaming large volumes of data
  • Legacy projects that already use ADO.NET
  • Constraints on external dependencies
  • Teams with deep ADO.NET expertise

Drawbacks:

// A lot of boilerplate
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("SELECT * FROM Users WHERE IsActive = @IsActive", connection))
{
    command.Parameters.AddWithValue("@IsActive", true);
    await connection.OpenAsync();

    using (var reader = await command.ExecuteReaderAsync())
    {
        var users = new List<User>();
        while (await reader.ReadAsync())
        {
            users.Add(new User
            {
                Id = reader.GetInt32(0),
                Name = reader.GetString(1),
                Email = reader.GetString(2),
                // ... more fields, by hand
            });
        }
        return users;
    }
}

Note: the ecosystem's ado-sp generator does not use AddWithValue — it infers nvarchar(4000) and silently kills the index — nor does it read columns by position. See generador-crud.


Code examples

A CRUD operation with Dapper

// 1. Repository interface
public interface IUserRepository
{
    Task<User> GetByIdAsync(int id);
    Task<IEnumerable<User>> GetAllAsync();
    Task<int> CreateAsync(User user);
    Task<bool> UpdateAsync(User user);
    Task<bool> DeleteAsync(int id);
}

// 2. Implementation with Dapper
public class UserRepository : IUserRepository
{
    private readonly IDbConnection _connection;

    public UserRepository(IDbConnection connection)
    {
        _connection = connection;
    }

    public async Task<User> GetByIdAsync(int id)
    {
        var sql = "SELECT * FROM Users WHERE Id = @Id";
        return await _connection.QueryFirstOrDefaultAsync<User>(sql, new { Id = id });
    }

    public async Task<IEnumerable<User>> GetAllAsync()
    {
        var sql = "SELECT * FROM Users WHERE IsActive = 1";
        return await _connection.QueryAsync<User>(sql);
    }

    public async Task<int> CreateAsync(User user)
    {
        var sql = @"INSERT INTO Users (Name, Email, IsActive)
                    VALUES (@Name, @Email, @IsActive);
                    SELECT CAST(SCOPE_IDENTITY() as int)";
        return await _connection.ExecuteScalarAsync<int>(sql, user);
    }

    public async Task<bool> UpdateAsync(User user)
    {
        var sql = @"UPDATE Users
                    SET Name = @Name, Email = @Email, IsActive = @IsActive
                    WHERE Id = @Id";
        var affectedRows = await _connection.ExecuteAsync(sql, user);
        return affectedRows > 0;
    }

    public async Task<bool> DeleteAsync(int id)
    {
        var sql = "DELETE FROM Users WHERE Id = @Id";
        var affectedRows = await _connection.ExecuteAsync(sql, new { Id = id });
        return affectedRows > 0;
    }
}

Setting it up in a .NET project

Setup with Dapper

1. Install the NuGet packages:

dotnet add package Dapper
dotnet add package Microsoft.Data.SqlClient

2. Configure it in Program.cs:

// Register IDbConnection in DI
builder.Services.AddScoped<IDbConnection>(sp =>
    new SqlConnection(builder.Configuration.GetConnectionString("DefaultConnection"))
);

// Register the repositories
builder.Services.AddScoped<IUserRepository, UserRepository>();

3. appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=MyDB;User Id=sa;Password=***;TrustServerCertificate=true"
  }
}

Note: in production, keep the connection string in the configured secrets vault.


Best practices with Dapper

DO

// Always use parameters (it prevents SQL injection)
var users = await connection.QueryAsync<User>(
    "SELECT * FROM Users WHERE Email = @Email",
    new { Email = email }
);

// Use async/await
public async Task<User> GetUserAsync(int id) { ... }

// Use stored procedures where they fit
var result = await connection.QueryAsync<User>(
    "sp_GetUsersByRole",
    new { Role = "Admin" },
    commandType: CommandType.StoredProcedure
);

// Map multiple result sets
var sql = @"
    SELECT * FROM Users WHERE Id = @Id;
    SELECT * FROM Orders WHERE UserId = @Id;
";
using (var multi = await connection.QueryMultipleAsync(sql, new { Id = id }))
{
    var user = await multi.ReadFirstOrDefaultAsync<User>();
    var orders = await multi.ReadAsync<Order>();
    user.Orders = orders.ToList();
}

// Use transactions when you need them
using (var transaction = connection.BeginTransaction())
{
    try
    {
        await connection.ExecuteAsync(sql1, param1, transaction);
        await connection.ExecuteAsync(sql2, param2, transaction);
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

DON'T

// Do NOT concatenate SQL strings (SQL injection vulnerability!)
var sql = $"SELECT * FROM Users WHERE Email = '{email}'"; // NEVER!

// Do NOT open the connection by hand when you do not need to
connection.Open(); // Dapper does it for you

// Do NOT use the synchronous call where async fits
var users = connection.Query<User>(sql); // use QueryAsync

// Do NOT forget to dispose connections
// Always use `using`, or dependency injection with a scope

Performance benchmarks

Operation: a simple SELECT (1,000 rows)

MethodTimeMemoryCode
Dapper12 ms1.2 MB3 lines
ADO.NET11 ms1.1 MB25 lines
Entity Framework45 ms3.5 MB5 lines

Conclusion:

  • Dapper: 99% of ADO.NET's performance with 88% less code
  • EF Core: slower but with more features (change tracking, migrations, and so on)

Learning resources

Dapper

ADO.NET


Final recommendation

For 90% of projects: use Dapper

Why:

  1. Significantly higher productivity
  2. Clean, maintainable code
  3. Performance almost identical to ADO.NET (the difference is < 10%)
  4. Active community and excellent support
  5. Gentle learning curve
  6. A good balance between control and simplicity

Only use ADO.NET if:

  • It is an existing legacy project already on ADO.NET
  • There is a specific constraint against external libraries
  • You need very specific optimizations (rare)

Version: 1.0 Last updated: 2025-10-27 Recommendation: Dapper in 90% of cases

Fuente: ovillo/_patron/01_Estructura_Tecnica/GUIA_ACCESO_DATOS_EN.md

Ovillo v1.31.0tag v1.31.0 (2026-10-06) · sin decisiones posteriores69 skills · 19 agents · 22 hooks · 3 reglas · 15 tools · 103 decisionesfuente: ovillo/_patron/01_Estructura_Tecnica/GUIA_ACCESO_DATOS_EN.mdCopyright 2026 Hugo Valer Rojas · Apache-2.0