Skip to content
Happy Programming Guide
Start learning
C#

C# and Databases

Talking to a database from C#: ADO.NET, Dapper and Entity Framework Core compared, with parameterised queries, migrations and the N+1 trap.

Servers mounted in a data centre rack

C# gives you three levels of database access. ADO.NET is the raw layer, Dapper is a thin mapper over it, and Entity Framework Core is a full object-relational mapper. Most projects use EF Core; knowing what the layers beneath do is what lets you diagnose a slow query when the abstraction gets in the way.

Choosing an approach#

ADO.NET Dapper EF Core
You write the SQL yes yes usually not
Maps rows to objects no yes yes
Change tracking no no yes
Migrations no no yes
Overhead none very low moderate
Best for full control read-heavy work most applications

They mix. A common arrangement is EF Core for ordinary reads and writes, with Dapper for the handful of reporting queries where you want the SQL yourself.

ADO.NET#

CSHARP
using Microsoft.Data.SqlClient;

const string sql = "SELECT Id, Name, Price FROM Products WHERE Price < @max";

await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();

await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@max", 20m);

await using var reader = await command.ExecuteReaderAsync();

while (await reader.ReadAsync())
{
    Console.WriteLine($"{reader.GetInt32(0)} {reader.GetString(1)}");
}

Verbose, and completely explicit about what happens. Note await using — connections and readers hold real resources, and leaking them exhausts the pool.

CSHARP
command.Parameters.Add("@max", SqlDbType.Decimal).Value = 20m;

Dapper#

Terminal
dotnet add package Dapper
CSHARP
using Dapper;

await using var connection = new SqlConnection(connectionString);

var products = await connection.QueryAsync<Product>(
    "SELECT Id, Name, Price FROM Products WHERE Price < @max",
    new { max = 20m });

var one = await connection.QuerySingleOrDefaultAsync<Product>(
    "SELECT Id, Name, Price FROM Products WHERE Id = @id",
    new { id = 42 });

var rows = await connection.ExecuteAsync(
    "UPDATE Products SET Price = @price WHERE Id = @id",
    new { price = 9.99m, id = 42 });

Your SQL, mapped to objects, with parameters taken from an anonymous object. Very little between you and the database, and very fast.

Entity Framework Core#

Terminal
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
CSHARP
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category? Category { get; set; }
}

public class ShopContext : DbContext
{
    public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }

    public DbSet<Product> Products => Set<Product>();
    public DbSet<Category> Categories => Set<Category>();

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Product>(entity =>
        {
            entity.Property(p => p.Name).IsRequired().HasMaxLength(120);
            entity.Property(p => p.Price).HasPrecision(10, 2);
            entity.HasIndex(p => p.Name);
        });
    }
}
CSHARP
// Registration
builder.Services.AddDbContext<ShopContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

Querying#

CSHARP
// Read
var cheap = await context.Products
    .Where(p => p.Price < 20m)
    .OrderBy(p => p.Name)
    .ToListAsync();

var one = await context.Products.FindAsync(42);

// Create
context.Products.Add(new Product { Name = "Pen", Price = 1.50m });
await context.SaveChangesAsync();

// Update - change tracking notices the assignment
var product = await context.Products.FindAsync(42);
if (product is not null)
{
    product.Price = 2.00m;
    await context.SaveChangesAsync();
}

// Delete
context.Products.Remove(product);
await context.SaveChangesAsync();

The update is the interesting one. You did not write an UPDATE statement — EF tracked the loaded entity, noticed the changed property, and generated SQL touching only that column.

Migrations#

Terminal
dotnet tool install --global dotnet-ef

dotnet ef migrations add AddProducts
dotnet ef database update
dotnet ef migrations remove          # undo the last, if not applied

A migration is generated C# describing the schema change, so it is reviewable, version-controlled and repeatable. Read the generated file before applying it — EF occasionally infers a destructive change, such as dropping and recreating a column, when you meant a rename.

The N+1 problem#

CSHARP
// One query for products, then one per product for its category
var products = await context.Products.ToListAsync();
foreach (var p in products)
{
    Console.WriteLine(p.Category?.Name);
}
CSHARP
// One query
var products = await context.Products
    .Include(p => p.Category)
    .ToListAsync();

On a page listing fifty products, that is the difference between fifty-one queries and one. It is the most common cause of a slow EF Core page by a wide margin.

Turn on logging in development so you can see it happening:

CSHARP
options.UseSqlServer(connectionString)
       .LogTo(Console.WriteLine, LogLevel.Information)
       .EnableSensitiveDataLogging();     // development only

Two habits that matter#

CSHARP
// Read-only queries do not need change tracking
var products = await context.Products
    .AsNoTracking()
    .Where(p => p.Price < 20m)
    .ToListAsync();

// Select only the columns you use
var summaries = await context.Products
    .Select(p => new { p.Id, p.Name })
    .ToListAsync();

AsNoTracking skips building the change-tracking snapshot, which is measurably faster and uses less memory on large result sets. A projection stops you pulling a large description column you never display.

Filtering in the database, not in memory#

CSHARP
// Loads every row, then filters in your process
var recent = (await context.Orders.ToListAsync())
    .Where(o => o.Date > cutoff);

// Filters in the database
var recent = await context.Orders
    .Where(o => o.Date > cutoff)
    .ToListAsync();

The position of ToListAsync decides where the work happens. Calling it early is the single most expensive mistake available in EF Core.

Transactions#

CSHARP
await using var transaction = await context.Database.BeginTransactionAsync();

try
{
    context.Accounts.Update(from);
    context.Accounts.Update(to);
    await context.SaveChangesAsync();

    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

A single SaveChangesAsync is already atomic, so an explicit transaction is only needed when you span several calls or mix in raw SQL.

Raw SQL when you need it#

CSHARP
var products = await context.Products
    .FromSqlInterpolated($"SELECT * FROM Products WHERE Price < {max}")
    .ToListAsync();

FromSqlInterpolated looks like string interpolation and is not — EF turns each embedded value into a parameter. Do not build the string yourself and pass it to FromSqlRaw; that is exactly the injection hole the method exists to avoid.

DbContext lifetime#

CSHARP
// Correct in ASP.NET Core - one per request, registered as scoped
builder.Services.AddDbContext<ShopContext>(...);

A DbContext is not thread-safe and is designed to be short-lived. Registering it as a singleton, or sharing one across concurrent work, produces intermittent errors about a second operation starting on the same context.

Questions people ask#

EF Core or Dapper?

EF Core for applications with substantial create, update and delete work, where change tracking and migrations save real effort. Dapper for read-heavy services and reporting, where you want the SQL and the lowest overhead.

Should I use the repository pattern with EF Core?

Often not. DbContext is already a unit of work and DbSet is already a repository, so wrapping them adds a layer that usually hides useful query capability. Named query methods on a service give you the testability without the ceremony.

How do I stop a migration dropping a column?

Read the generated migration before applying it, and edit it. EF cannot tell a rename from a drop-and-add, so it guesses — and the guess is destructive.

Where should the connection string live?

In configuration, with the password supplied by an environment variable or a secret manager. Never in source control.

Where to go next#

C# performance, where database access usually dominatesRead next

Keep reading

C#

C# Reflection and Attributes

Reading type information at run time, writing custom attributes, and the performance cost — plus source generators as the modern alternative.

5 min read

C#

C# and ASP.NET Core

Building web applications and APIs with ASP.NET Core: minimal APIs, controllers, dependency injection, middleware, validation and configuration.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *