Entity Framework Core interview questions and answers for .NET developers

Entity Framework interview questions check whether you know what SQL your LINQ turns into and what the DbContext is tracking while it runs. Expect questions on DbContext lifetime, change tracking and AsNoTracking, eager, explicit and lazy loading, the N+1 problem, relationships configured with the Fluent API, and migrations. Senior rounds focus on production: slow generated queries, concurrency conflicts, bulk updates, migrations on a live database, and how you test data access honestly.

By Published 8 min read

How Entity Framework comes up in .NET interviews

Entity Framework Core is the default object-relational mapper in modern .NET, so it appears in almost every C# backend interview, usually right after questions on ASP.NET Core. Some companies still run the older Entity Framework 6 on .NET Framework, and interviewers there may ask how the two differ. Most questions are practical: what this LINQ query sends to the database, why this page makes two hundred queries, why this update threw a concurrency exception. The web framework side is covered in .NET interview questions, and language features such as LINQ and async in C# interview questions.

  1. Concept checkDbContext, tracking, loading strategies, migrations and how EF maps classes to tables.
  2. Read a queryGiven a LINQ expression, say what SQL it produces, how many round trips it makes and what it loads into memory.
  3. Model a domainConfigure relationships, keys, owned types and indexes for a small domain such as orders or bookings.
  4. Production scenariosA slow endpoint, a deadlock during a migration, lost updates, or memory that grows in a worker service.

Entity Framework fundamentals questions

Basics for juniors and every first technical round
QuestionWhat it testsWhat a strong answer shows
What is a DbContext?Core modelA session with the database: it holds the connection, tracks loaded entities, builds queries and saves changes as one unit of work. A DbSet exposes one entity type for querying and adding.
What lifetime should a DbContext have in a web app?LifetimeScoped, one per request, which is what AddDbContext registers. It is not thread-safe, so it must not be shared across concurrent operations or kept as a singleton.
Code-first or database-first?WorkflowCode-first defines entities in C# and generates the schema through migrations. Database-first scaffolds classes from an existing schema. Teams pick by who owns the schema.
Conventions, data annotations or Fluent API?ConfigurationConventions infer keys and relationships from names. Annotations put simple rules on the class. The Fluent API in OnModelCreating (or IEntityTypeConfiguration classes) covers everything and keeps entities clean.
What does change tracking do?TrackingThe context remembers loaded entities and their original values, detects what changed, and SaveChanges writes only those changes.
What are entity states?State machineAdded, Unchanged, Modified, Deleted and Detached. SaveChanges turns them into INSERT, UPDATE and DELETE statements.
When do you use AsNoTracking?Read performanceFor read-only queries, such as API responses. It skips the tracking snapshot, uses less memory and is faster; the results cannot be saved back without attaching.
Find versus FirstOrDefault?Identity mapFind looks up the primary key in the tracked entities first and only queries the database if it is not there. FirstOrDefault always queries.
What is a migration?Schema changesA generated class describing schema changes between two model versions, with a snapshot of the model. Migrations are applied in order and recorded in a history table.
Is SaveChanges transactional?AtomicityYes. With a relational provider, all changes in one SaveChanges call run in a transaction, so they succeed or fail together.
Basics for juniors and every first technical round. Scroll sideways on a small screen.

Querying and loading questions

  • What is deferred execution? A LINQ query against a DbSet is an IQueryable that builds an expression tree. Nothing runs until you enumerate it or call ToList, First, Count and similar, and each enumeration runs it again.
  • What happens if EF cannot translate part of a query? Modern EF Core throws instead of silently pulling the whole table into memory, except for the final Select projection, which may run on the client. The fix is to rewrite the expression or switch to client evaluation explicitly with AsEnumerable after filtering.
  • Eager, explicit or lazy loading? Eager loading with Include fetches related data in the same query. Explicit loading calls Load on a navigation when you decide you need it. Lazy loading (through proxies, opt-in) loads on first access, which is convenient and the usual cause of N+1.
  • What is the N+1 problem? One query for a list, then one more per item as code touches a navigation property in a loop. Fix it with Include, or better, a projection that selects exactly the fields the page needs.
  • Why can Include make things worse? Including two collections in one query joins them, and the rows multiply: three posts and four contributors return twelve rows for one blog. A split query (AsSplitQuery) sends one query per collection instead.
  • Why prefer projections for read endpoints? Selecting into a DTO reads only the needed columns, needs no tracking and avoids loading whole graphs. It is usually the fastest option for APIs.
  • How do you see the SQL EF generates? ToQueryString on a query, logging through the context options, or a database profiler. Reading the SQL is the first step in any performance question.
  • When should you use raw SQL? For queries LINQ cannot express well or for tuned reports. Use FromSql or ExecuteSql with interpolated strings, which become parameters; never concatenate user input into SQL.
  • What are compiled queries? Queries whose translation is cached up front with EF.CompileAsyncQuery, saving a little work on very hot paths. EF already caches translations, so measure before reaching for this.
// 1. N+1 when lazy loading is enabled: one query for orders, one per customer.
var orders = await db.Orders.Where(o => o.Status == OrderStatus.Open).ToListAsync(ct);
foreach (var o in orders)
    Console.WriteLine($"{o.Id} {o.Customer.Name}");

// 2. Eager loading: one query, but full Order and Customer entities are tracked.
var withCustomers = await db.Orders
    .Include(o => o.Customer)
    .Where(o => o.Status == OrderStatus.Open)
    .ToListAsync(ct);

// 3. Projection: one query, only three columns, nothing tracked.
var rows = await db.Orders
    .Where(o => o.Status == OrderStatus.Open)
    .Select(o => new OpenOrderRow(o.Id, o.Customer.Name, o.Total))
    .ToListAsync(ct);
Three ways to load orders with customer names. The first triggers N+1 with lazy loading on; the second loads whole entities; the third reads only what the response needs. Documented EF Core API; not executed here.
-- One blog with 3 posts and 4 contributors.
SELECT COUNT(*) AS single_query_rows
FROM blogs b
LEFT JOIN posts p ON p.blog_id = b.id
LEFT JOIN contributors c ON c.blog_id = b.id;        -- 12

SELECT (SELECT COUNT(*) FROM blogs)
     + (SELECT COUNT(*) FROM posts WHERE blog_id = 1)
     + (SELECT COUNT(*) FROM contributors WHERE blog_id = 1) AS split_query_rows;  -- 8
Why two collection Includes in one query multiply rows. Run in SQLite: the single joined query returns 12 rows for one blog, while three separate queries return 1 + 3 + 4 = 8.

Modeling and writing data

Intermediate questions on mapping and saving
QuestionWhat it testsWhat a strong answer shows
How do you configure a one-to-many relationship?RelationshipsHasOne/WithMany with a foreign key property, plus the delete behavior. Say whether deleting the parent should cascade, restrict or set null, because the default may not be what the business wants.
How does EF Core handle many-to-many?Join tablesRecent versions map it with skip navigations and an implicit join table; use an explicit join entity when the link carries data such as a role or date.
What is an owned type?Value objectsA type with no identity of its own, such as an Address, stored in the owner's table (or a separate one) and loaded with it.
What are value converters for?MappingTranslating a property to a database type and back: enums to strings, strongly typed ids to Guid, or a small list to a JSON column.
What is a shadow property?Hidden columnsA column EF knows about that has no property on the class, such as a foreign key or a LastUpdated audit field, set through the change tracker.
How do you detect lost updates?ConcurrencyMark a concurrency token, typically a row version column. EF adds it to the WHERE clause of updates, and if no row matches it throws DbUpdateConcurrencyException, which you handle by reloading, merging or asking the user.
How do you update many rows without loading them?Set-based writesExecuteUpdate and ExecuteDelete (EF Core 7 and later) run one UPDATE or DELETE in the database. They bypass the change tracker, so tracked entities in the same context can be stale.
How do you run several SaveChanges calls in one transaction?TransactionsBegin a transaction on db.Database, call SaveChanges as needed, then commit. With retrying execution strategies, wrap the whole block in the strategy so a retry replays all of it.
Intermediate questions on mapping and saving. Scroll sideways on a small screen.
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> b)
    {
        b.HasKey(o => o.Id);
        b.Property(o => o.Number).HasMaxLength(20).IsRequired();
        b.HasIndex(o => o.Number).IsUnique();

        b.HasOne(o => o.Customer)
         .WithMany(c => c.Orders)
         .HasForeignKey(o => o.CustomerId)
         .OnDelete(DeleteBehavior.Restrict);

        b.OwnsOne(o => o.ShippingAddress);

        b.Property(o => o.RowVersion).IsRowVersion();   // concurrency token
        b.HasQueryFilter(o => !o.IsDeleted);             // soft delete
    }
}
Fluent configuration with a row-version concurrency token, an owned address, a unique index and a soft-delete filter. Not executed here.

Senior Entity Framework and scenario questions

Production scenarios
ScenarioLikely causeWhat to say you would check
An endpoint got slow as data grew.Query shapeLog the SQL and its plan. Look for N+1 from lazy loading, a missing index on a filter column, Include chains loading too much, or a Count over a huge unfiltered set.
A worker service's memory climbs for hours.Long-lived contextOne DbContext reused for the whole run keeps tracking every entity. Create a scope per unit of work with IServiceScopeFactory, or use AsNoTracking and clear the tracker between batches.
"A second operation was started on this context" errors.Concurrency on one contextParallel tasks sharing a DbContext, often via Task.WhenAll or an un-awaited call. Each concurrent operation needs its own context.
The migration locked a big table during deploy.Schema changes on live dataAdding an index or a non-null column rewrote or locked the table. Generate the SQL script, review it with a DBA, use online index options where the database supports them, and split risky changes into several releases.
Two users editing the same record overwrite each other.Optimistic concurrencyAdd a row version token and handle DbUpdateConcurrencyException with a clear user-facing choice.
Tests pass but production queries fail.Unrealistic test providerThe in-memory provider does not behave like a relational database: no real SQL translation, constraints or transactions. Test against the same database engine, for example in a container.
Production scenarios. Scroll sideways on a small screen.
  • How should migrations reach production? Not by calling Migrate at app startup on several instances at once. Generate an idempotent SQL script or a migration bundle in CI, review it, and apply it as a deliberate deploy step with a rollback plan.
  • What do global query filters solve, and what is the risk? Soft delete and multi-tenancy rules applied to every query on an entity. The risk is forgetting they exist; IgnoreQueryFilters is needed for admin views, and a filter on the tenant must never be skipped by accident.
  • What are interceptors used for? Hooking into commands, connections and SaveChanges: auditing, setting timestamps, adding query hints or logging slow commands without touching every repository.
  • Should you wrap EF Core in a repository? DbContext already acts as a unit of work and DbSet as a repository. A thin layer can help with testing or a domain boundary, but a generic repository that hides IQueryable often throws away the features you need.
  • How does DbContext pooling help? It reuses context instances to cut allocation cost on very busy services. It requires the context to hold no per-request state beyond what EF resets.
  • EF Core or a micro-ORM such as Dapper? EF for rich domain models, change tracking and migrations; Dapper for hand-tuned SQL on hot read paths. Many teams use both in one codebase.

Fictional example

Answering "This orders page makes over two hundred queries"
Interviewer
The orders list page shows 50 orders with customer names and item counts, and the database log shows more than two hundred queries per page load. What is happening and how do you fix it?
Candidate
That count suggests N+1 on more than one navigation: one query for the orders, then one per order for the customer and another per order for the items. Lazy loading is probably on and the view touches Customer and Items in a loop. I would confirm with the SQL log or ToQueryString. The fix I would pick is a projection: select order id, number, customer name and Items.Count into a row type, with AsNoTracking implied since it is a projection. That becomes a single query with a join and a subquery for the count. I would check the plan for an index on the status filter, and add a test that counts commands for the page so the problem cannot come back unnoticed.

Entity Framework practice plan

  • Days 1 and 2: build a small model with three related entities, configured with the Fluent API, and create and apply migrations to a local database.
  • Day 3: turn on SQL logging. Write the same read with lazy loading, Include, split queries and a projection, and count the queries each one sends.
  • Day 4: add a row version, open two contexts, update the same row in both and handle the concurrency exception.
  • Day 5: replace a load-modify-save loop with ExecuteUpdate and measure the difference; note what the change tracker no longer sees.
  • Day 6: write integration tests against a real database engine, not the in-memory provider, and generate an idempotent migration script.
  • Day 7: mock round: explain tracking, N+1 and migration safety out loud, each in under two minutes.

Database fundamentals behind EF questions, such as indexes, joins and isolation levels, are in SQL interview questions.

EF answers land best when you name the SQL a query produces before discussing fixes, and a transcript makes it obvious when you skipped that step. Natively, an AI interview assistant for Mac and Windows, captures a practice .NET round as text on your computer for you to review later. During practice it can read a LINQ query or an exception from a screenshot and talk through the likely SQL, and with Pro or the free trial it can use the résumé and job description you add to focus on the stack in the posting. Session notes are saved alongside the transcript.

Questions people ask

What Entity Framework questions are asked in .NET interviews?

What a DbContext is and its lifetime, change tracking and AsNoTracking, deferred execution, eager, explicit and lazy loading, the N+1 problem, Fluent API relationships, migrations, optimistic concurrency and raw SQL safety.

What is the N+1 problem in Entity Framework?

Loading a list in one query and then triggering another query for each item, usually through lazy loading in a loop. Fix it with Include or, for read endpoints, a projection that selects only the needed fields.

What is the difference between EF Core and Entity Framework 6?

EF6 is the older framework built for .NET Framework. EF Core is the cross-platform rewrite used with modern .NET, with different APIs and features, and it is where new development happens.

When should I use AsNoTracking?

For read-only queries whose results you will not save, such as API responses and reports. It skips the change tracker, which saves memory and time.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP