Web & DataComplete guide

Entity Framework Core

Entity Framework Core is the modern .NET object-relational mapper for translating LINQ into database commands, mapping domain state to relational schemas, coordinating units of work, and evolving schemas through reviewed migrations.

Overview

Entity Framework Core sits between application code and a database provider, but it does not remove the need to understand relational design or SQL. A short-lived DbContext holds model metadata, a database connection strategy, query composition, change tracking, transactions, and SaveChanges behavior. Providers translate expression trees into database-specific SQL, so the same LINQ can behave differently across SQLite, PostgreSQL, SQL Server, or another provider. Production-ready use requires intentional mappings and constraints, bounded projections, query inspection, optimistic concurrency, migration discipline, provider-realistic tests, and operational ownership of schema deployment.

What you will learn

  • Explain the roles of DbContext, the model, providers, change tracking, SaveChanges, and the underlying database.
  • Map aggregates with keys, relationships, owned types, conversions, indexes, constraints, and concurrency tokens.
  • Shape efficient read models with projection, AsNoTracking, bounded pagination, query tags, and generated-SQL inspection.
  • Coordinate atomic writes with transactions while allowing database constraints to protect invariants.
  • Create, review, test, script, and deploy migrations as versioned production artifacts.
  • Test important behavior against SQLite and the real production provider without relying on EF Core's in-memory substitute.

Prerequisites

  • Comfort with C#, LINQ, asynchronous methods, cancellation tokens, and dependency injection.
  • Basic relational concepts including tables, primary and foreign keys, indexes, joins, constraints, and transactions.
  • The .NET 10 SDK; Docker Desktop is optional for the PostgreSQL/Testcontainers verification path.

When to use Entity Framework Core

Good fit

  • Transactional .NET applications that benefit from strongly typed LINQ, unit-of-work change tracking, relationship mapping, and managed schema evolution.
  • Teams that want most CRUD and aggregate persistence expressed in C# while retaining access to SQL, transactions, interceptors, and provider-specific features.
  • Workloads where developers will inspect generated SQL, measure important queries, and treat migrations and database constraints as first-class engineering artifacts.

Choose another approach when

  • A read-heavy path requiring tightly controlled hand-written SQL or specialized database features for nearly every query; Dapper or the provider API may be clearer.
  • Bulk ingestion, analytical processing, or set-based maintenance where database-native commands and bulk tooling are the primary abstraction.
  • A design that assumes one LINQ query is portable and equally efficient across all providers without provider-specific verification.

Key concepts

DbContext lifetime

A DbContext is a short-lived unit of work that coordinates queries, tracked state, transactions, and persistence; it is not thread-safe.

Model and Fluent API

Entity configuration maps CLR types to keys, columns, conversions, relationships, owned values, indexes, constraints, and concurrency behavior.

Query translation

The provider translates a composable LINQ expression tree into database-specific commands; translation and performance must be verified.

Change tracking

Snapshots and entity states let SaveChanges calculate inserts, updates, and deletes, while no-tracking queries avoid that cost for read models.

Transactions and constraints

SaveChanges is transactional for one batch, explicit transactions span multiple operations, and database constraints remain the final consistency boundary.

Optimistic concurrency

A concurrency token participates in an update predicate so stale writers fail instead of silently overwriting newer state.

Migrations

Versioned schema operations capture model changes for review, testing, scripting, deployment, and rollback planning.

Provider behavior

SQLite, PostgreSQL, SQL Server, and other providers differ in types, SQL translation, locking, migrations, functions, and operational capabilities.

Architecture

Application commands and queries use a short-lived DbContext. EF Core applies model metadata and provider translation to execute parameterized SQL inside database transactions, then materializes results or reconciles tracked changes.

Application use case
DbContext
Model + change tracker
Database provider
SQL + transaction
Relational database

Conceptual architecture · Adapt to your system context

Implementation walkthrough

Build the critical path deliberately, then verify its observable behavior.

  1. 01
    Choose the provider deliberately

    Install the provider for the production database and keep provider versions compatible with the EF Core runtime.

  2. 02
    Define aggregate boundaries

    Model entities and value objects around business invariants before persistence configuration leaks into every domain type.

  3. 03
    Configure the relational model

    Use IEntityTypeConfiguration classes for keys, relationships, owned types, lengths, precision, conversions, indexes, constraints, and delete behavior.

  4. 04
    Shape read queries

    Filter, order, project, and bound results in the database; use AsNoTracking when the unit of work will not modify returned entities.

  5. 05
    Protect write workflows

    Use database constraints, explicit transactions when one SaveChanges is insufficient, and concurrency tokens for competing writers.

  6. 06
    Create and review migrations

    Generate a migration, inspect every operation, test it on representative data, and create an idempotent script or migration bundle for deployment.

  7. 07
    Verify real providers

    Use fast relational tests locally and container-backed tests for behaviors whose types, SQL, locking, or migrations depend on the production provider.

Code example

The dedicated sample projects a bounded read model in SQL, disables tracking, tags the query for diagnostics, and keeps cancellation explicit.

OrderQueries.cs
return await db.Orders
    .TagWith("Open order summaries")
    .AsNoTracking()
    .Where(order => order.Status == OrderStatus.Placed)
    .OrderByDescending(order => order.CreatedAtUtc)
    .ThenBy(order => order.Id)
    .Select(order => new OrderSummary(
        order.Id,
        order.CreatedAtUtc,
        order.Customer.Name,
        order.Items.Count,
        order.Items.Sum(item => item.UnitPrice * item.Quantity)))
    .Skip(page * pageSize)
    .Take(pageSize)
    .ToListAsync(cancellationToken);

Testing strategy

EF Core tests should prove relational behavior, not just exercise LINQ against an in-memory collection.

  • Use SQLite or another relational provider for fast tests that need migrations, foreign keys, unique constraints, transactions, and concurrency behavior.
  • Avoid the EF Core in-memory provider when relational translation or constraints are part of the requirement.
  • Run focused Testcontainers tests against the production provider for provider-specific SQL, types, locking, migrations, and functions.
  • Assert observable outcomes and important SQL shape without coupling every test to incidental generated text.
  • Keep external provider tests explicit and deterministic so a missing Docker engine is reported honestly rather than causing mysterious failures.

Security considerations

An ORM reduces repetitive SQL construction but does not make data access automatically safe.

  • Prefer LINQ parameters, ExecuteSqlInterpolated, or provider parameters; never concatenate untrusted values into raw SQL.
  • Store connection strings in environment-specific secret providers and use a least-privilege database identity per workload.
  • Do not enable sensitive-data logging in production because parameter values and personal data can enter logs.
  • Bound queries and command timeouts to reduce resource-exhaustion risk, and authorize access before constructing tenant or resource queries.
  • Review migration permissions separately from runtime permissions; an application account rarely needs schema-owner rights.

Performance and scalability

The dominant EF Core cost is usually database work and data shape, not the ORM call itself.

  • Project only required columns, bound every list, and choose pagination that remains efficient at the expected depth.
  • Use AsNoTracking for read-only materialization and compiled queries only after measurement shows compilation overhead matters.
  • Prevent N+1 queries by projecting related values or loading relationships intentionally; do not add Include automatically.
  • Inspect ToQueryString output, database query plans, row counts, round trips, indexes, and telemetry for critical paths.
  • Batch writes where appropriate and use provider-native bulk operations when change tracking is the wrong tool for the volume.

Deployment and operations

Schema evolution is an operational workflow with availability, compatibility, backup, and rollback consequences.

  • Review generated migrations and test them against production-like schema size and data before release.
  • Deploy provider-supported scripts or migration bundles from one controlled job rather than racing migrations across application instances.
  • Use expand-and-contract changes when old and new application versions may run concurrently during rollout.
  • Back up data, define rollback or forward-fix procedures, monitor locks and duration, and separate provider-specific migration sets when supporting multiple databases.
  • Pin and audit EF Core, provider, native database, and migration-tool dependencies as one compatible release set.

Common problems and fixes

A LINQ query throws a translation exception.

Likely cause: The expression contains a .NET method or shape the selected provider cannot translate.

Fix: Rewrite the query using supported expressions, split database and in-memory work at an intentional bounded point, and inspect generated SQL.

A page is slow or sends many database commands.

Likely cause: The query loads too many columns or rows, uses offset pagination deeply, lacks an index, or triggers N+1 relationship loading.

Fix: Capture command telemetry, project the exact read model, bound results, inspect the plan, add the right index, and remove accidental per-row queries.

SaveChanges throws DbUpdateConcurrencyException.

Likely cause: Another writer changed or deleted a row after this context loaded its concurrency token.

Fix: Reload current values and apply a documented retry, merge, or conflict response; do not blindly overwrite the winner.

A migration works locally but fails in production.

Likely cause: Production has different provider behavior, data volume, locks, permissions, schema history, or incompatible application versions.

Fix: Test the generated artifact on a production-like copy, use expand-and-contract changes, validate migration history, and deploy from a controlled identity.

A DbContext reports disposed or concurrent-operation errors.

Likely cause: The context escaped its unit of work, was shared across threads, or a query was not awaited before another operation started.

Fix: Create one short-lived context per unit of work, await each operation, and use IDbContextFactory for parallel or background flows.

Best practices

  • Keep DbContext short-lived and never share one instance across concurrent operations.
  • Use explicit Fluent API mappings and database constraints for important invariants.
  • Project bounded read models and use AsNoTracking when updates are not required.
  • Inspect generated SQL and database plans for critical queries instead of reasoning from LINQ alone.
  • Use concurrency tokens and handle conflicts as an application outcome.
  • Review and test migrations as production code, deploying them through one controlled workflow.
  • Test provider-specific behavior against the real provider and keep separate migrations when providers diverge.
  • Pass cancellation tokens and configure realistic command timeouts for database work.

Production checklist

  • EF Core runtime, database provider, native dependencies, and migration tool are pinned to compatible audited versions.
  • Connection strings come from a secret provider and runtime identities have least-privilege permissions.
  • Critical mappings include deliberate lengths, precision, indexes, constraints, delete behavior, and concurrency tokens.
  • Important queries are projected, bounded, observable, cancellation-aware, and verified with generated SQL and query plans.
  • N+1 risks, deep pagination, large writes, transaction boundaries, retries, and command timeouts are tested under realistic load.
  • Migrations are reviewed, tested on representative data, backed by recovery procedures, and deployed once through a controlled job.
  • Provider-realistic integration tests cover schema, constraints, translation, and concurrency without depending on shared developer databases.

Common interview questions

What is the recommended DbContext lifetime in a web application?

Scoped is the common default because it aligns a context with one request or unit of work. A context is not thread-safe and should not be shared across concurrent operations.

What causes the N+1 query problem?

The application first loads a set of parent rows and then issues another query for each parent's related data, often through repeated explicit or lazy loading.

When should AsNoTracking be used?

Use it for read-only materialization when entities will not be changed in the current unit of work. Projection to a DTO often avoids entity tracking entirely.

How does optimistic concurrency work in EF Core?

A configured token is included in the update or delete predicate. If no row matches the original token, EF Core throws DbUpdateConcurrencyException so the application can resolve the conflict.

Why should migrations not automatically run from every production application instance?

Concurrent instances can race, application identities gain excessive schema permissions, and long migrations can block startup or traffic. A controlled deployment job provides clearer ownership and recovery.

Why can the same LINQ query behave differently across providers?

Each provider owns translation, type mapping, functions, SQL generation, and database capabilities. Portability must be verified rather than assumed.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

EF Core Order Management

A focused .NET 10 console sample demonstrating Fluent API mapping, owned types, relationships, constraints, projected no-tracking queries, transactions, optimistic concurrency, migrations, SQLite tests, and opt-in PostgreSQL verification with Testcontainers.

EF Core 10.NET 10SQLitePostgreSQLxUnit
dedicated-samplemigrationsconcurrencyquery-performancetestcontainers
Run
dotnet run --project src/EfCoreOrderManagement
Test
dotnet test EfCoreOrderManagement.slnx