efcore-patterns

Bonnes pratiques Entity Framework Core incluant NoTracking par défaut, fractionnement des requêtes pour les collections de navigation, gestion des migrations, service de migration dédié et pièges courants à éviter.

Qu'est-ce que efcore-patterns ?

Ce skill fournit un ensemble de bonnes pratiques essentielles pour Entity Framework Core (EF Core), destinées aux développeurs .NET qui souhaitent optimiser les performances, gérer efficacement les migrations et éviter les erreurs courantes. Il couvre cinq grands modèles : la désactivation du suivi des changements par défaut (NoTracking), l'utilisation des commandes CLI pour les migrations, la séparation des migrations dans un service dédié, la gestion des échecs transitoires avec ExecutionStrategy, et les opérations en masse avec ExecuteUpdate/ExecuteDelete. Les plateformes supportées incluent ASP.NET Core, .NET Aspire, PostgreSQL et SQL Server. L'utilisation de ce skill permet d'améliorer les performances des applications à forte charge de lecture, de maintenir une base de données synchronisée via des migrations automatisées, et d'éviter des bugs silencieux comme les mises à jour non suivies ou les requêtes N+1.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/efcore-patterns

Installed? Explore more Développement et programmation skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Modèles Entity Framework Core

Quand utiliser ce skill

Utilisez ce skill lorsque :

  • Vous configurez EF Core dans un nouveau projet
  • Vous optimisez les performances des requêtes
  • Vous gérez les migrations de base de données
  • Vous intégrez EF Core avec .NET Aspire
  • Vous déboguez des problèmes de suivi des changements
  • Vous chargez plusieurs collections de navigation efficacement (fractionnement des requêtes)

Principes fondamentaux

  1. NoTracking par défaut - La plupart des requêtes sont en lecture seule ; optez explicitement pour le suivi
  2. Ne modifiez jamais les migrations manuellement - Utilisez toujours les commandes CLI
  3. Service de migration dédié - Séparez l'exécution des migrations du démarrage de l'application
  4. ExecutionStrategy pour les tentatives - Gérez les échecs de base de données transitoires
  5. Mises à jour explicites - Avec NoTracking, marquez explicitement les entités pour la mise à jour

Modèle 1 : NoTracking par défaut

Configurez votre DbContext pour désactiver le suivi des changements par défaut. Cela améliore les performances pour les charges de travail à forte proportion de lectures.

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
        // Désactive le suivi des changements par défaut pour de meilleures performances sur les requêtes en lecture seule
        // Utilisez .AsTracking() explicitement pour les requêtes qui nécessitent de suivre les changements
        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }

    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Customer> Customers => Set<Customer>();
}

Quand NoTracking est actif

Les requêtes en lecture seule fonctionnent normalement :

// ✅ Lecture rapide - pas de surcharge de suivi
var orders = await dbContext.Orders
    .Where(o => o.Status == OrderStatus.Pending)
    .ToListAsync();

Les écritures nécessitent une gestion explicite :

// ❌ MAUVAIS - Entité non suivie, SaveChanges ne fait rien
var order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
await dbContext.SaveChangesAsync(); // Rien ne se passe !

// ✅ CORRECT - Marquer explicitement l'entité pour mise à jour
var order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
dbContext.Orders.Update(order); // Marque toute l'entité comme modifiée
await dbContext.SaveChangesAsync();

// ✅ ÉGALEMENT CORRECT - Utiliser AsTracking() pour la requête
var order = await dbContext.Orders
    .AsTracking()
    .FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
await dbContext.SaveChangesAsync(); // Fonctionne !

Quand utiliser le suivi

ScénarioUtiliser le suivi ?Pourquoi
Afficher des données dans l'UINonLecture seule, pas de mises à jour
Points de terminaison API GETNonRenvoyer des données, pas de mutations
Mettre à jour une seule entitéOui ou Update() expliciteBesoin de sauvegarder les changements
Mise à jour complexe avec navigationOuiLe suivi gère les relations
Opérations par lotsNon + ExecuteUpdatePlus efficace

Modèle Add/Update explicite

public class OrderService
{
    private readonly ApplicationDbContext _db;

    // CREATE - Toujours utiliser Add (fonctionne indépendamment du suivi)
    public async Task<Order> CreateOrderAsync(Order order)
    {
        _db.Orders.Add(order);
        await _db.SaveChangesAsync();
        return order;
    }

    // UPDATE - Marquer explicitement comme modifié
    public async Task UpdateOrderStatusAsync(Guid orderId, OrderStatus newStatus)
    {
        var order = await _db.Orders.FirstOrDefaultAsync(o => o.Id == orderId)
            ?? throw new NotFoundException($"Commande {orderId} non trouvée");

        order.Status = newStatus;
        order.UpdatedAt = DateTimeOffset.UtcNow;

        // Marquer explicitement comme modifié car DbContext utilise NoTracking par défaut
        _db.Orders.Update(order);
        await _db.SaveChangesAsync();
    }

    // DELETE - Attacher et supprimer
    public async Task DeleteOrderAsync(Guid orderId)
    {
        var order = new Order { Id = orderId };
        _db.Orders.Remove(order);
        await _db.SaveChangesAsync();
    }
}

Modèle 2 : Ne modifiez jamais les migrations manuellement

CRITIQUE : Utilisez toujours les commandes CLI EF Core pour gérer les migrations. Ne jamais :

  • Modifier manuellement les fichiers de migration (sauf pour du SQL personnalisé dans Up()/Down())
  • Supprimer directement les fichiers de migration
  • Renommer les fichiers de migration
  • Copier les migrations entre projets

Création de migrations

# Créer une nouvelle migration
dotnet ef migrations add AddCustomerTable \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# Avec un DbContext spécifique (si vous en avez plusieurs)
dotnet ef migrations add AddCustomerTable \
    --context ApplicationDbContext \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

Suppression de migrations

# Supprimer la dernière migration (si elle n'a pas encore été appliquée)
dotnet ef migrations remove \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# NE JAMAIS faire ceci :
# rm Migrations/20240101_AddCustomerTable.cs  # ❌ MAUVAIS !

Application de migrations

# Appliquer toutes les migrations en attente
dotnet ef database update \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# Appliquer jusqu'à une migration spécifique
dotnet ef database update AddCustomerTable \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# Revenir à une migration précédente
dotnet ef database update PreviousMigrationName \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

Génération de scripts SQL

# Générer un script SQL pour toutes les migrations
dotnet ef migrations script \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api \
    --output migrations.sql

# Générer un script idempotent (sûr à exécuter plusieurs fois)
dotnet ef migrations script \
    --idempotent \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

Modèle 3 : Service de migration dédié avec Aspire

Séparez l'exécution des migrations de votre application principale à l'aide d'un service de migration dédié. Cela garantit :

  • Les migrations sont terminées avant le démarrage de l'application
  • Une séparation nette des responsabilités
  • Un amorçage contrôlé dans les environnements de test

Structure du projet

src/
├── MyApp.AppHost/           # Orchestration Aspire
├── MyApp.Api/               # Application principale
├── MyApp.Infrastructure/    # DbContext et migrations
└── MyApp.MigrationService/  # Exécuteur de migration dédié

Program.cs du MigrationService

using MyApp.Infrastructure.Data;
using MyApp.MigrationService;
using Microsoft.EntityFrameworkCore;

var builder = Host.CreateApplicationBuilder(args);

// Ajouter les valeurs par défaut du service Aspire
builder.AddServiceDefaults();

// Ajouter le DbContext PostgreSQL
var connectionString = builder.Configuration.GetConnectionString("appdb")
    ?? throw new InvalidOperationException("Chaîne de connexion 'appdb' non trouvée.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(connectionString, npgsqlOptions =>
        npgsqlOptions.MigrationsAssembly("MyApp.Infrastructure")));

// Ajouter le worker de migration
builder.Services.AddHostedService<MigrationWorker>();

var host = builder.Build();
host.Run();

MigrationWorker.cs

public class MigrationWorker : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IHostApplicationLifetime _hostApplicationLifetime;
    private readonly ILogger<MigrationWorker> _logger;

    public MigrationWorker(
        IServiceProvider serviceProvider,
        IHostApplicationLifetime hostApplicationLifetime,
        ILogger<MigrationWorker> logger)
    {
        _serviceProvider = serviceProvider;
        _hostApplicationLifetime = hostApplicationLifetime;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Service de migration en cours de démarrage...");

        try
        {
            using var scope = _serviceProvider.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

            await RunMigrationsAsync(dbContext, stoppingToken);

            _logger.LogInformation("Service de migration terminé avec succès.");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Échec du service de migration : {Error}", ex.Message);
            throw;
        }
        finally
        {
            // Arrêter l'application une fois les migrations terminées
            _hostApplicationLifetime.StopApplication();
        }
    }

    private async Task RunMigrationsAsync(ApplicationDbContext dbContext, CancellationToken ct)
    {
        // Utiliser la stratégie d'exécution pour la gestion des échecs transitoires
        var strategy = dbContext.Database.CreateExecutionStrategy();

        await strategy.ExecuteAsync(async () =>
        {
            var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync(ct);

            if (pendingMigrations.Any())
            {
                _logger.LogInformation("Application de {Count} migration(s) en attente...",
                    pendingMigrations.Count());

                await dbContext.Database.MigrateAsync(ct);

                _logger.LogInformation("Migrations appliquées avec succès.");
            }
            else
            {
                _logger.LogInformation("Aucune migration en attente. La base de données est à jour.");
            }
        });
    }
}

Configuration AppHost

var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("postgres");
var db = postgres.AddDatabase("appdb");

// Les migrations s'exécutent en premier, puis se terminent
var migrations = builder.AddProject<Projects.MyApp_MigrationService>("migrations")
    .WaitFor(db)
    .WithReference(db);

// L'API attend que les migrations soient terminées
var api = builder.AddProject<Projects.MyApp_Api>("api")
    .WaitForCompletion(migrations)  // Clé : attend la fin des migrations
    .WithReference(db);

Modèle 4 : ExecutionStrategy pour les échecs transitoires

Utilisez toujours CreateExecutionStrategy() pour les opérations qui peuvent échouer de manière transitoire :

public async Task UpdateWithRetryAsync(Guid id, Action<Order> update)
{
    var strategy = _dbContext.Database.CreateExecutionStrategy();

    await strategy.ExecuteAsync(async () =>
    {
        var order = await _dbContext.Orders
            .AsTracking()
            .FirstOrDefaultAsync(o => o.Id == id);

        if (order is null) return;

        update(order);
        await _dbContext.SaveChangesAsync();
    });
}

Important : Vous ne pouvez pas utiliser CreateExecutionStrategy() avec des transactions initiées par l'utilisateur. Si vous avez besoin de transactions avec tentatives :

var strategy = _dbContext.Database.CreateExecutionStrategy();

await strategy.ExecuteAsync(async () =>
{
    // La transaction doit être À L'INTÉRIEUR du rappel de la stratégie
    await using var transaction = await _dbContext.Database.BeginTransactionAsync();

    try
    {
        // ... vos opérations ...
        await _dbContext.SaveChangesAsync();
        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
});

Modèle 5 : Opérations en masse avec ExecuteUpdate/ExecuteDelete

Pour les opérations en masse, utilisez ExecuteUpdateAsync et ExecuteDeleteAsync d'EF Core 7+ plutôt que de charger les entités :

// ❌ LENT - Charge toutes les entités en mémoire
var expiredOrders = await _db.Orders
    .Where(o => o.ExpiresAt < DateTimeOffset.UtcNow)
    .ToListAsync();

foreach (var order in expiredOrders)
{
    order.Status = OrderStatus.Expired;
}
await _db.SaveChangesAsync();

// ✅ RAPIDE - Une seule instruction SQL UPDATE
await _db.Orders
    .Where(o => o.ExpiresAt < DateTimeOffset.UtcNow)
    .ExecuteUpdateAsync(setters => setters
        .SetProperty(o => o.Status, OrderStatus.Expired)
        .SetProperty(o => o.UpdatedAt, DateTimeOffset.UtcNow));

// ✅ RAPIDE - Une seule instruction SQL DELETE
await _db.Orders
    .Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt < cutoffDate)
    .ExecuteDeleteAsync();

Pièges courants

1. Oublier de mettre à jour avec NoTracking

// ❌ Échec silencieux - entité non suivie
var customer = await _db.Customers.FindAsync(id);
customer.Name = "Nouveau nom";
await _db.SaveChangesAsync(); // Ne fait rien !

// ✅ Mise à jour explicite
var customer = await _db.Customers.FindAsync(id);
customer.Name = "Nouveau nom";
_db.Customers.Update(customer);
await _db.SaveChangesAsync();

2. Problème de requêtes N+1

// ❌ Requêtes N+1 - une requête par commande
var customers = await _db.Customers.ToListAsync();
foreach (var customer in customers)
{
    var orders = customer.Orders; // Le chargement paresseux déclenche une requête
}

// ✅ Chargement hâtif - une seule requête
var customers = await _db.Customers
    .Include(c => c.Orders)
    .ToListAsync();

3. Conflits de suivi avec plusieurs instances de DbContext

// ❌ Conflit de suivi - entité suivie par un contexte différent
var order1 = await _db1.Orders.AsTracking().FindAsync(id);
var order2 = await _db2.Orders.AsTracking().FindAsync(id);
order2.Status = OrderStatus.Shipped;
await _db2.SaveChangesAsync(); // Peut lever une exception ou se comporter de manière inattendue

// ✅ Utiliser un seul contexte ou détacher d'abord
_db1.Entry(order1).State = EntityState.Detached;

4. Ne pas utiliser Async de manière cohérente

// ❌ Appel bloquant dans un contexte asynchrone
var orders = _db.Orders.ToList(); // Bloque le thread

// ✅ Async tout du long
var orders = await _db.Orders.ToListAsync();

5. Effectuer des requêtes à l'intérieur de boucles

// ❌ Requête par itération
foreach (var orderId in orderIds)
{
    var order = await _db.Orders.FindAsync(orderId);
    // traiter la commande
}

// ✅ Une seule requête
var orders = await _db.Orders
    .Where(o => orderIds.Contains(o.Id))
    .ToListAsync();

Durée de vie du DbContext dans l'injection de dépendances

ASP.NET Core (Scoped par défaut)

// Scoped = une instance par requête HTTP
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(connectionString));

…

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

Skills associés