skip to content

Entity Framework Core

2 roadmaps90 questionsupdated

Microsoft's ORM for .NET, an LTS release at version 10: LINQ translated to SQL, a change tracker that writes edits back, and migrations. Interviewers read EF Core depth as backend seniority.

on this pageshow

guide

overview

~2 min

Entity Framework Core is Microsoft's object-relational mapper for .NET. You describe entities and their relationships in C#, query them with LINQ, and EF Core translates those queries into SQL for a database provider such as SQL Server, PostgreSQL or SQLite, then keeps an eye on the objects it hands back so that edits can be written back as inserts, updates and deletes. Interviewers treat it as a window onto backend judgement: anyone can call `SaveChanges`, so the questions test whether you can say which SQL a line of LINQ produces, how many round trips a page costs, and what the context is holding in memory while it runs. The hub follows the life of an entity. [DbContext & Modeling](/topics/be-ef-core-dbcontext-modeling) is how classes become tables and how the context itself is configured. [LINQ Querying](/topics/be-ef-core-linq-queries) is the read side: what translates, what does not, and when to drop to raw SQL or set-based updates. [Change Tracking](/topics/be-ef-core-change-tracking) is the write side, from entity states through transactions to optimistic concurrency. [Navigations & Loading](/topics/be-ef-core-relationships-loading) covers relationships, cascade rules and how related rows arrive, which is where N+1 queries begin. [Schema Change Workflow](/topics/be-ef-core-migrations) evolves the database through migrations and asks where they should run in production. [Speed & Portability](/topics/be-ef-core-performance) is about measuring before tuning, and about what changes when the provider does. Junior rounds stay on vocabulary: what a context is, which states an entity can be in, what `Include` does, what a migration contains. Middle and senior rounds turn diagnostic — a slow dashboard, a lost update, a migration that would drop a column, a test suite that passes against a stand-in database and fails against the real one — and expect you to name the setting or query shape responsible. Learn the model and the context first, then querying and change tracking together, because they are two halves of one unit of work. Loading strategies, migrations and tuning all assume both.

primer

### A context is a short-lived unit of work The `DbContext` bundles a connection, a change tracker and a reference to the cached model. It is designed to serve one request or one business operation, used by one piece of code at a time. Lifetime explains a surprising share of bugs: a context kept alive too long accumulates tracked entities and serves stale ones, and a context shared across threads breaks outright. Pooling recycles instances to save allocation, after resetting them; it does not make sharing safe. ### The model is a mapping you choose once Conventions infer keys, nullability and table names; data annotations and the fluent API override them. Owned and complex types, value conversions and an inheritance strategy decide the shape of the tables. Because the database outlives the code that first mapped it, interviewers treat these as long-lived decisions and expect you to know what the default would have done before you changed it. ### LINQ describes a query; the provider runs it An `IQueryable` is an expression tree, not a result. No SQL is sent until it is enumerated or a terminal operator such as `ToListAsync` or `CountAsync` executes. EF Core then translates what it can into SQL, and since client-side evaluation is limited to the outermost projection, an untranslatable method elsewhere is an error rather than a silent in-memory filter. Good answers say where each part of a query runs, and verify by reading the generated SQL. ### Tracking makes writes easy and reads expensive Tracked entities carry original-value snapshots and one-instance-per-key bookkeeping so that `SaveChanges` can work out what changed. That pays for itself on a write path and is pure overhead on a read-only page, where no-tracking queries and projections into DTOs skip it. Set-based `ExecuteUpdate` and `ExecuteDelete` skip the tracker entirely, and with it everything that hangs off `SaveChanges`. ### Related data arrives only when you ask for it A navigation gets filled by eager loading, explicit loading, lazy loading, or fix-up from rows the context already tracks. Each choice trades round trips against row volume. N+1 queries on one side and row multiplication from wide joins on the other are the two failure modes most loading questions circle. ### The schema moves through reviewed migrations Model changes are diffed against a snapshot to produce migration code, which is a draft: renames, data moves and type changes often need hand edits. Where and how migrations are applied in production is an operational choice with consequences for permissions, rollback and deploy order. ### Concurrency is optimistic and opt-in EF Core takes no row locks of its own. Without a concurrency token, the last write wins; with one, a stale update fails at save time, and deciding what to do about the conflict is the application's job.

DbContext
The unit-of-work object between application code and the database. It holds the model, a connection and a change tracker, and is meant to live for one operation.
DbSet
A property on the context that exposes one entity type, both as the root for LINQ queries and as the place to add or remove instances.
Fluent API
Model configuration written in code, in OnModelCreating or per-entity configuration classes. It overrides conventions and data annotations and can express mappings attributes cannot.
Change tracker
The context component that remembers each tracked entity's state and original values, and compares them with current values to decide what SaveChanges must write.
EntityState
The state the tracker assigns an entity: Detached, Unchanged, Added, Modified or Deleted. It decides whether SaveChanges inserts, updates, deletes or ignores that entity.
Navigation property
A property pointing from one entity to a related entity or collection. The database stores the foreign key; the navigation is the object-side view of that link.
Owned and complex types
Ways to map a value object with no identity of its own as part of its owner. Owned types are entities internally; complex types are true values without a hidden key.
Global query filter
A predicate configured on an entity type that EF Core adds to every query against it, commonly for soft delete or tenant isolation. A single query can opt out.
No-tracking query
A query whose results are not attached to the change tracker. Cheaper for reads, but edits to the returned objects are not saved unless they are attached later.
Split query
A mode that loads included collections with one SQL statement each instead of one joined statement, avoiding row multiplication at the cost of extra round trips.
Concurrency token
A property whose original value is added to the WHERE clause of updates and deletes, so the write affects no row if someone changed it since it was read.
Migration
A generated class describing one schema change and its reverse, applied in order and recorded in a history table inside the target database.
Model snapshot
A generated file describing the model as of the latest migration. The next migration is computed by diffing the current model against it.
Database provider
The package that adapts EF Core to one database: its SQL dialect, type mappings, function translations and migration operations.
Execution strategy
A policy that retries an operation after a transient database failure. With retries enabled, a manually opened transaction must run inside the strategy so the whole unit can replay.
Interceptor
A registered hook that runs around EF Core operations such as commands, connections or SaveChanges, used for auditing, logging or adjusting behaviour in one place.

Follow one web request. The ASP.NET Core container registers the context with a scoped lifetime, so each request gets its own instance, configured through options that choose the provider, the connection string, logging and any retry policy. The first time a context type is used, EF Core builds its model from conventions, annotations and fluent configuration and keeps it for the life of the process; every later instance reuses that model. A query starts as LINQ against a `DbSet`. On execution EF Core compiles the expression tree, the provider renders SQL, and the rows come back as entities or projected objects. Tracking queries register what they return with the change tracker. When code edits those objects and calls `SaveChanges`, the tracker detects the differences, the provider generates and batches commands, and they run inside one transaction unless the caller already opened one. ```csharp builder.Services.AddDbContext<ShopContext>(options => options .UseNpgsql(connectionString) // provider: dialect, type mapping .LogTo(Console.WriteLine)); // see what is actually sent // inside a request: one scoped context, one unit of work var order = await db.Orders .Include(o => o.Lines) // related rows, same round trip .SingleAsync(o => o.Id == id); // executes; result is tracked order.Status = OrderStatus.Shipped; // tracker compares with snapshot await db.SaveChangesAsync(); // UPDATE ... in one transaction ``` The other sections attach to this path rather than sitting beside it: - **Loading** decides whether a navigation is filled in the same query, in a later one, or on first access. - **Concurrency tokens** make an UPDATE conditional, so a stale write fails at `SaveChanges` instead of quietly winning. - **Set-based and raw SQL** operations leave the path: they execute immediately and the tracker never learns about them. - **Migrations** run outside the request, through design-time tooling that reads the same model to produce schema changes. - **Interceptors and logging** sit on the command path, which is where any performance investigation should start.

  1. DbContext & Modeling →

    The context, its lifetime and how classes map to tables: everything else in the hub assumes this model exists.

  2. LINQ Querying →

    The read side: what LINQ translates to, where it fails to translate, and when raw SQL or set-based updates are the better tool.

  3. Change Tracking →

    The write side: entity states, what SaveChanges does as a unit, transactions and optimistic concurrency.

  4. Navigations & Loading →

    Relationships, cascade rules and loading strategies, which only make sense once querying and tracking are clear.

  5. Schema Change Workflow →

    How the schema follows the model, and where migrations should be applied once real data is at stake.

  6. Speed & Portability →

    Tuning and provider differences, which build on every earlier section and reward measuring over guessing.

  • Sharing one DbContext across requests or parallel tasks: it supports one operation at a time, and a long-lived context also piles up tracked entities and serves stale data.

  • Assuming a LINQ call runs in the database because it compiled: an untranslatable method outside the final projection throws, so read the generated SQL instead of guessing it.

  • Loading tracked entities for a read-only page when a projection or AsNoTracking would do; snapshots and identity bookkeeping cost memory and time with no write to justify them.

  • Turning on lazy loading for convenience and then touching navigations in a loop, so one page becomes a query per row — see Include, Explicit & Lazy.

  • Including two sibling collections in one query and blaming the database for the slowness, when the joined result multiplies rows per parent.

  • Expecting audit interceptors or concurrency checks to cover ExecuteUpdate, ExecuteDelete or raw SQL; those bypass SaveChanges and everything attached to it.

  • Shipping a scaffolded migration unread: a rename can be generated as a drop and an add, which loses the column's data on deploy.

  • Trusting tests on the in-memory provider: it is not relational, so constraints, transactions and SQL translation go unexercised until production.

  • Building raw SQL by pasting user input into a plain-string API instead of using the overloads that send values as parameters.

  • Applying migrations at application startup by default: it gives the app account schema rights and ties schema changes to every instance's boot, where a reviewed script or bundle keeps them a separate step.

This guide assumes EF Core 10, the long-term-support release that ships alongside .NET 10; since EF Core 6, even-numbered releases are LTS and odd-numbered ones have short-term support. Plenty of production code runs on 8 or older, and several questions have a different answer depending on the release: - **3.0** stopped silently evaluating untranslatable query parts in memory; from then on only the final projection may run on the client, and anything else throws. - **5.0** added split queries, filtered `Include`, many-to-many relationships without a join class, and table-per-type mapping. - **7.0** added set-based `ExecuteUpdate` and `ExecuteDelete`, table-per-concrete-type mapping and JSON columns. - **8.0** introduced complex types for value objects. - **9.0** added `UseSeeding` and made migrating refuse to run when the model holds changes no migration captures. When an answer depends on one of these — client evaluation, inheritance mapping, bulk updates, seeding — say which release you are describing. Knowing that a pre-3.0 codebase may hide in-memory filtering, or that a pre-7.0 one has no set-based update short of raw SQL, makes legacy code much faster to read.

EF Core is the default data-access layer for ASP.NET Core applications, registered through the same dependency-injection container and usually scoped per request. Its nearest alternative in .NET is Dapper, a micro-ORM that maps the results of SQL you write yourself onto objects: no change tracking, no LINQ translation, no migrations, and full control over every statement. Many teams use both — EF Core for writes and most reads, Dapper or plain ADO.NET for a handful of hand-tuned queries. NHibernate, a port of Hibernate that predates EF Core, still runs in many older codebases. Outside .NET the closest counterpart is Hibernate behind JPA on the JVM, built on the same ideas of a session, change tracking and lazy loading, so experience carries across in both directions. Database support comes from providers, some shipped by Microsoft and others maintained by database communities, such as Npgsql for PostgreSQL. Schema changes can be owned by EF Core migrations or by a dedicated tool such as Flyway, DbUp or Liquibase when several applications share the database; interviewers expect you to say who owns the schema. For tests, the common position is to run against the production engine in a container rather than a stand-in provider.

explore

report an issue with this guide →

questions

90 · 6 sections

In EF Core 10, what do the [Key], [Required], [MaxLength], [Column] and [Index] attributes change in the model, and what do conventions decide without them?

level: juniorimportance: must knowfreq 68%
basics
~20 s

By convention EF Core makes a property named Id or <Type>Id the key, takes nullability from the C# type, maps strings without a length and names the table after the DbSet. [Key], [Required], [MaxLength], [Column] and [Index] override those choices.

open as a page

In EF Core 10, what do a DbContext and its DbSet<T> properties do, and when does a change actually reach the database?

level: juniorimportance: must knowfreq 74%
basics
~20 s

A DbContext is EF Core's session with a database: it owns the model, tracks entities and turns their changes into SQL. Each DbSet<T> is the query root for one entity type. Nothing is written until SaveChanges or SaveChangesAsync runs.

open as a page

In EF Core 10, how does an abstract Payment class with CardPayment, BankTransferPayment and VoucherPayment subclasses map to tables by default?

level: juniorimportance: must knowfreq 50%
basics
~20 s

By default EF Core uses table-per-hierarchy (TPH): every payment type goes into one Payments table, with a shadow Discriminator column holding the class name, such as CardPayment, and nullable columns for each subclass's properties. Subclasses must be added to the model explicitly.

open as a page

In EF Core 10, how is an OrderStatus enum property stored by default, and how do you store its name with HasConversion<string>()?

level: juniorimportance: must knowfreq 52%
basics
~20 s

EF Core stores an enum as its underlying integer type by default, so a plain OrderStatus becomes an int column. HasConversion<string>() picks the built-in enum-to-string converter and the column holds names such as "Shipped"; add HasMaxLength so the column is not unbounded.

open as a page

In EF Core, when a convention, a data annotation and the fluent API configure one property differently, which wins, and where do IEntityTypeConfiguration<T> classes fit?

level: middleimportance: must knowfreq 62%
basics
~20 s

The fluent API wins over data annotations, which win over conventions; among fluent calls the last one wins. IEntityTypeConfiguration<T> is the same fluent API moved into one class per entity and applied from OnModelCreating, so it has fluent precedence.

open as a page

In EF Core 10, how do you hide soft-deleted forum posts from every query with HasQueryFilter, and how does a moderator page still see them?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Configure modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted) in OnModelCreating; EF adds that condition to every query of Post, including Include and navigations. A moderator query calls IgnoreQueryFilters() to switch filters off for that one query.

open as a page

In EF Core 10, how does FromSql run a raw SQL query with a user-supplied value, and what can you compose on top of it?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Call db.Readings.FromSql($"SELECT ... WHERE "DeviceId" = {deviceId}"): FromSql takes a FormattableString and sends each interpolated value as a DbParameter, never as SQL text. LINQ after it wraps your SQL as a subquery, and results are tracked entities.

open as a page

To archive millions of old sensor readings in EF Core 10, why use ExecuteUpdateAsync or ExecuteDeleteAsync instead of load-modify-SaveChanges, and what do they bypass?

level: middleimportance: must knowfreq 57%
basics
~20 s

ExecuteUpdateAsync and ExecuteDeleteAsync turn a LINQ query into one SQL UPDATE or DELETE that runs immediately, without loading or tracking rows, and return the affected row count. They bypass the change tracker, SaveChanges, its concurrency checks and any implicit transaction.

open as a page

In EF Core 10, what happens when a query calls a C# method EF cannot translate, inside Where versus inside the final Select?

level: middleimportance: must knowfreq 64%
basics
~20 s

Inside Where, EF Core throws an InvalidOperationException saying the expression could not be translated. Inside the final Select it fetches the needed columns and runs the method on the client: only the top-level projection may be client-evaluated.

open as a page

An EF Core 10 project dashboard loads each project's work items and members in one query and has become slow; how do AsSplitQuery and QuerySplittingBehavior help, and what do they cost?

level: seniorimportance: must knowfreq 55%
basics
~10 s

Loading two sibling collections in one SQL statement multiplies rows per project. AsSplitQuery, or UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) globally, sends one statement per collection instead, at the cost of extra round trips and no single-snapshot consistency.

open as a page

In EF Core 10, what does one SaveChangesAsync call do with the pending changes, and what happens when one of its statements fails?

level: juniorimportance: must knowfreq 72%
basics
~20 s

SaveChangesAsync detects changes, turns Added, Modified and Deleted entries into INSERT, UPDATE and DELETE commands, batches them, and runs them atomically. If any statement fails, the transaction rolls back, a DbUpdateException is thrown and the tracked states are kept.

open as a page

In EF Core 10, what are the five EntityState values, and what does SaveChanges do with an entity in each one?

level: juniorimportance: must knowfreq 72%
basics
~10 s

EntityState has five values: Detached, Unchanged, Added, Modified and Deleted. SaveChanges inserts Added entities, updates Modified ones, deletes Deleted ones and skips the rest; afterwards Added and Modified become Unchanged and Deleted become Detached.

open as a page

In EF Core 10, how does [ConcurrencyCheck] or IsConcurrencyToken differ from [Timestamp] or IsRowVersion, and what does each add to an UPDATE?

level: middleimportance: must knowfreq 62%
basics
~20 s

Both put the property's original value into the WHERE of every UPDATE and DELETE. [ConcurrencyCheck] / IsConcurrencyToken leaves changing it to your code; [Timestamp] / IsRowVersion also marks it generated on add and update, so the database bumps it.

open as a page

In EF Core 10, when do you need Database.BeginTransactionAsync, and how do savepoints behave inside a transaction you began?

level: middleimportance: must knowfreq 55%
basics
~20 s

Use BeginTransactionAsync when several SaveChanges, ExecuteUpdate or raw SQL calls must commit together. Inside it, SaveChanges sets a savepoint before writing and rolls back to it on failure, so the transaction stays usable; named savepoints work by hand too.

open as a page

In EF Core 10, how do you save a detached customer profile posted by a mobile app without rewriting every column?

level: middleimportance: must knowfreq 65%
basics
~20 s

Update marks every property Modified, so the UPDATE rewrites all columns. To write less, Attach the object and set IsModified on the fields the endpoint owns, or load the row and copy the DTO with CurrentValues.SetValues, which marks only values that differ.

open as a page

In EF Core 10, how do Include and ThenInclude load related entities, and what does a navigation hold when a query omits them?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Include loads a navigation in the same query as its owner; ThenInclude goes one level deeper. A navigation left out is not queried: it stays null or empty unless the context already tracks those rows or lazy loading is on.

open as a page

In EF Core 10, how do you configure a one-to-many relationship with HasOne, WithMany and HasForeignKey, and what makes it required or optional?

level: juniorimportance: must knowfreq 72%
basics
~10 s

In OnModelCreating, call HasOne(c => c.Department).WithMany(d => d.Courses).HasForeignKey(c => c.DepartmentId) on the dependent. A non-nullable foreign key makes the relationship required; a nullable one such as int? makes it optional.

open as a page

An EF Core 10 admin page lists a playlist's tracks with artist and album and logs one SQL query per track - how do lazy-loading proxies cause that, and how do you fix it?

level: middleimportance: must knowfreq 70%
basics
~20 s

With UseLazyLoadingProxies, each virtual navigation loads on first access, so reading track.Artist and track.Album in the loop sends queries per track. Load them up front with Include/ThenInclude or a Select projection, and switch lazy loading off.

open as a page

In EF Core 10, what happens to a course's enrolments when the course is deleted, and how do OnDelete and DeleteBehavior change that?

level: middleimportance: must knowfreq 66%
basics
~20 s

With the default required relationship (Cascade), EF Core deletes tracked enrolments itself and the database's ON DELETE CASCADE removes untracked ones. OnDelete(DeleteBehavior...) changes both what EF Core does to tracked rows and the constraint migrations create.

open as a page

In EF Core 10, how does explicit loading through Entry().Collection() and Entry().Reference() work, and when do you call Query() instead of Load()?

level: middleimportance: should knowfreq 45%
basics
~20 s

Explicit loading fetches one navigation of an entity you already hold: db.Entry(x).Collection(...) or .Reference(...), then LoadAsync(). Query() instead returns an IQueryable over that navigation, to count, filter or page related rows without loading them all.

open as a page

In EF Core 10, what does dotnet ef database update do, and how do you move a database back to an earlier migration?

level: juniorimportance: must knowfreq 70%
basics
~20 s

It applies every migration not yet recorded in __EFMigrationsHistory, in id order, and adds a history row for each. Passing a migration name moves the database to that point, running Down on newer migrations; 0 reverts them all.

open as a page

In EF Core 10, what does dotnet ef migrations add generate, and what do a migration's Up and Down methods hold?

level: juniorimportance: must knowfreq 74%
basics
~20 s

It writes a timestamped migration class whose Up holds MigrationBuilder operations that apply the model change and whose Down holds the inverse, plus a Designer file and a rewritten model snapshot. Nothing reaches the database until migrations are applied.

open as a page

In EF Core 10, how does Database.EnsureCreated differ from Database.Migrate, and why must one database never use both?

level: middleimportance: must knowfreq 55%
basics
~20 s

EnsureCreated builds the database and tables from the current model only when they are missing, keeps no migration history and never alters them later. Migrate applies and records migrations. Mixing them makes Migrate recreate existing tables and fail.

open as a page

In EF Core 10, renaming Car.Plate to LicensePlate while also shortening its max length scaffolds DropColumn and AddColumn; why, and how do you fix the migration?

level: seniorimportance: must knowfreq 55%
basics
~20 s

EF Core pairs old and new columns only by name, property name or identical shape; a rename plus a length change matches none, so it drops and adds. Rewrite Up as RenameColumn plus AlterColumn and mirror it in Down.

open as a page

In EF Core 10, what is a migration bundle, how do you build efbundle for a Linux release pipeline, and what does it need when it runs?

level: middleimportance: should knowfreq 42%
basics
~20 s

A bundle is an executable, efbundle by default, that does what dotnet ef database update does without the SDK or source. Build it in CI with --self-contained -r linux-x64, then run it with --connection and the right environment.

open as a page

In EF Core 10, how do you make a DbContext log the SQL it sends, and what do EnableSensitiveDataLogging and EnableDetailedErrors add?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Call LogTo on DbContextOptionsBuilder, or let AddDbContext use the host's ILoggerFactory, and EF Core logs each command with its SQL. EnableSensitiveDataLogging adds parameter and key values; EnableDetailedErrors names the property behind a failed value read.

open as a page

In EF Core 10, why does a read-only product search that projects with Select into a DTO usually beat loading full Product entities?

level: juniorimportance: must knowfreq 66%
basics
~20 s

A Select projection makes EF Core fetch only the projected columns and materialize small DTOs that are never tracked, so it skips change-tracking snapshots and identity resolution; loading full tracked entities transfers and allocates far more for the same page.

open as a page

Why can EF Core 10 tests on the in-memory provider pass while the same code fails against SQL Server or PostgreSQL?

level: middleimportance: must knowfreq 58%
basics
~20 s

EF Core's in-memory provider is not a relational database: it runs LINQ as .NET code over collections, sends no SQL, supports no transactions or raw SQL and enforces no unique indexes or foreign keys, so it hides what production databases add.

open as a page

In an EF Core 10 app on PostgreSQL, which packages must share EF Core's major version, and what breaks when they don't?

level: juniorimportance: should knowfreq 40%
basics
~10 s

Every EF Core package moves as one major: the Npgsql provider 10.x, Microsoft.EntityFrameworkCore.Design, test providers such as Microsoft.EntityFrameworkCore.Sqlite and the dotnet-ef tool. Mixing majors brings NU1608 warnings, tool warnings or runtime missing-member failures.

open as a page

With the Npgsql EF Core provider 10, how do you map a C# enum to a native PostgreSQL enum type, and what does MapEnum set up?

level: middleimportance: should knowfreq 32%
basics
~20 s

Call MapEnum<T>() inside UseNpgsql's options callback. The Npgsql provider then maps the enum on the data source it builds and adds the PostgreSQL enum to the model, so migrations emit CREATE TYPE and the column uses that type.

open as a page