Entity Framework Core Interview Questions
Last updated 2026-11-19
Entity Framework Core is the default data access layer for .NET, and interviews test whether you understand what it does behind the API: change tracking, when queries run, how related data is loaded and what SQL ends up on the wire. The classic follow-up is the N+1 query problem.
The answers target EF Core 8 on .NET 8. Queries use LINQ, so read this with the LINQ questions. DbContext lifetime and dependency injection are explained further on the .NET Core page.
| Version | EF Core 8 on .NET 8 |
|---|---|
| Core types | DbContext, DbSet<T>, ChangeTracker |
| Approaches | Code-first with migrations, or database-first scaffolding |
What to be able to explain
- DbContext as unit of work and DbSet as repository-like entry point.
- When a query is sent to the database: on enumeration, not when you write it.
- Change tracking: how SaveChanges knows what to INSERT, UPDATE and DELETE.
- Loading related data without N+1.
- How to detect and handle concurrent updates.
Entity Framework Core Interview Questions: questions with worked answers
1 What is EF Core and what do DbContext and DbSet do?
easyEF Core is an object-relational mapper that maps C# classes to tables and translates LINQ queries to SQL. DbContext represents a session with the database and acts as a unit of work: it tracks changes to loaded entities and writes them together with SaveChanges. Each DbSet<T> property exposes a table or entity type for querying and adding. A DbContext is lightweight and not thread safe.
csharppublic class ShopContext(DbContextOptions<ShopContext> o) : DbContext(o) { public DbSet<Customer> Customers => Set<Customer>(); public DbSet<Order> Orders => Set<Order>(); }2 Code-first versus database-first, and how do migrations work?
mediumCode-first starts from C# entity classes and generates the schema through migrations; database-first scaffolds classes from an existing database with dotnet ef dbcontext scaffold. A migration is a generated C# class with Up and Down methods plus a model snapshot, applied in order, with the applied ones recorded in the __EFMigrationsHistory table. For production, generate a SQL script or a migration bundle instead of running Migrate at app start on many instances.
csharpdotnet ef migrations add AddOrders dotnet ef database update dotnet ef migrations script --idempotent -o deploy.sql dotnet ef migrations bundle3 Explain the N+1 problem and how to fix it.
hardN+1 means one query loads a list of parents and then one extra query per parent loads its related data, turning 100 orders into 101 round trips. It happens with lazy loading or with a query inside a loop. Fix it with eager loading (Include and ThenInclude), a projection that selects only what you need, or a single batch query. Projection with Select is usually the best, because it also avoids loading unneeded columns.
csharp// N+1 with lazy loading proxies: one query for orders, then one per order var orders = await db.Orders.ToListAsync(); foreach (var o in orders) Console.WriteLine(o.Customer.Name); // Eager loading: one JOIN query var withCust = await db.Orders.Include(o => o.Customer).ToListAsync(); // Projection: only two columns var rows = await db.Orders.Select(o => new { o.Id, Customer = o.Customer.Name }).ToListAsync();4 Eager, explicit and lazy loading: how do they differ?
mediumEager loading brings related data in the initial query with Include. Explicit loading fetches it on demand with Entry(x).Collection(...).Load(). Lazy loading, which needs the Proxies package and virtual navigation properties, loads automatically on first access, which is convenient but hides queries and invites N+1. EF Core does not enable lazy loading by default. Also remember that async lazy loading does not exist, so lazy loads block a thread.
5 What is the Cartesian explosion problem and what does AsSplitQuery do?
mediumIncluding several collection navigations in one query produces a single JOIN whose result set multiplies the rows (orders times items times payments), transferring huge duplicated data. AsSplitQuery makes EF issue one query per collection, which avoids the multiplication but costs several round trips and can see inconsistent data if rows change in between. Measure both ways, or project to a DTO.
csharpvar data = await db.Orders .Include(o => o.Items) .Include(o => o.Payments) .AsSplitQuery() .ToListAsync();6 What does AsNoTracking do and when do you use it?
easyBy default EF keeps a snapshot of every entity returned and watches for changes, which costs memory and CPU. AsNoTracking skips tracking, making read-only queries faster and lighter. Use it for queries whose results are only displayed. Do not call SaveChanges expecting changes to such entities to be saved. AsNoTrackingWithIdentityResolution fixes duplicated instances for repeated rows.
csharpvar list = await db.Products.AsNoTracking().Where(p => p.Price > 100).ToListAsync();7 How does change tracking work, and what are the entity states?
mediumThe ChangeTracker holds each tracked entity with a state: Detached, Unchanged, Added, Modified or Deleted. DetectChanges compares current values to the snapshot taken at load, and SaveChanges generates INSERT, UPDATE or DELETE commands for the changed entities inside one transaction. You can set the state yourself with Entry(entity).State, or call Update, which marks every property of a disconnected entity as modified, writing all columns.
csharpvar p = await db.Products.FindAsync(1); p!.Price = 120; Console.WriteLine(db.Entry(p).State); // Modified await db.SaveChangesAsync(); // UPDATE ... SET Price = 120 WHERE Id = 18 When does a query actually execute? Predict the behaviour.
mediumA LINQ query over a DbSet is an IQueryable that is only a description until you enumerate it with ToList, foreach, First, Count or similar. Composing Where and OrderBy before that adds to the same SQL statement. Calling ToList too early pulls the whole table into memory, and filtering afterwards happens in C#. Since EF Core 3.0 expressions that cannot be translated throw instead of silently running in memory.
csharpvar q = db.Products.Where(p => p.Price > 100); // no SQL yet q = q.OrderBy(p => p.Name); // still no SQL var first = await q.FirstOrDefaultAsync(); // SELECT TOP(1) ... executes now9 How do you handle concurrency conflicts?
hardOptimistic concurrency uses a concurrency token, typically a rowversion column marked with [Timestamp] or IsRowVersion, that EF adds to the WHERE clause of UPDATE and DELETE. If another user changed the row, zero rows are affected and EF throws DbUpdateConcurrencyException. Handle it by reloading the database values, then choosing client wins, database wins or merging, and retrying. Pessimistic locking needs explicit SQL or transactions.
csharppublic class Product { public int Id { get; set; } public decimal Price { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = null!; } try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { var entry = ex.Entries.Single(); await entry.ReloadAsync(); // database wins; or merge values }10 How do you configure relationships, and what is the order of precedence between conventions, data annotations and the Fluent API?
mediumConventions apply first, data annotations override conventions, and the Fluent API in OnModelCreating overrides both. Relationships are configured with HasOne, WithMany, HasForeignKey and OnDelete. EF Core 5 added many-to-many with skip navigations, with an implicit join table you can customise with UsingEntity.
csharpprotected override void OnModelCreating(ModelBuilder b) { b.Entity<Order>() .HasOne(o => o.Customer).WithMany(c => c.Orders) .HasForeignKey(o => o.CustomerId) .OnDelete(DeleteBehavior.Restrict); b.Entity<Student>().HasMany(s => s.Courses).WithMany(c => c.Students); }11 What should the lifetime of a DbContext be, and why is it not a singleton?
mediumRegister it as scoped, so each web request gets its own instance, which is cheap to create and tracks only that request's entities. A DbContext is not thread safe and a long-lived one accumulates tracked entities and stale data. Use AddDbContextPool to reuse instances for performance, and IDbContextFactory<T> when you need short-lived contexts in singletons, background services or Blazor components.
csharpbuilder.Services.AddDbContext<ShopContext>(o => o.UseSqlServer(conn)); builder.Services.AddDbContextFactory<ShopContext>(o => o.UseSqlServer(conn));12 FromSqlRaw versus FromSqlInterpolated: what is the injection risk?
mediumBoth run raw SQL and map the results to entities. FromSqlInterpolated and FromSql with an interpolated string turn each placeholder into a database parameter, which is safe. FromSqlRaw with a concatenated or manually interpolated string builds the SQL text by hand and is vulnerable to SQL injection. Always pass values as parameters.
csharpstring name = userInput; var safe = db.Customers.FromSql($"SELECT * FROM Customers WHERE Name = {name}").ToList(); // UNSAFE: db.Customers.FromSqlRaw("SELECT * FROM Customers WHERE Name = '" + name + "'")13 What are ExecuteUpdate and ExecuteDelete?
mediumAdded in EF Core 7, they run set-based UPDATE and DELETE statements directly in the database without loading entities or using change tracking. They are much faster for bulk changes. They bypass the change tracker, so tracked entities are not updated, and they run immediately without waiting for SaveChanges.
csharpint n = await db.Products .Where(p => p.Discontinued) .ExecuteUpdateAsync(s => s.SetProperty(p => p.Price, p => p.Price * 0.9m)); await db.Orders.Where(o => o.Created < cutoff).ExecuteDeleteAsync();14 What are global query filters, and how do you implement soft delete?
mediumA global query filter is a LINQ predicate configured per entity type that EF appends to every query, commonly for soft delete or multi-tenancy. Entities flagged as deleted are then hidden unless you call IgnoreQueryFilters. Remember to convert real deletes into updates, for example in an interceptor or by overriding SaveChanges.
csharpmodelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted); var all = await db.Posts.IgnoreQueryFilters().ToListAsync();15 How do transactions work in EF Core?
mediumSaveChanges wraps all its changes in one implicit transaction, so a single call is atomic. For multiple SaveChanges calls or mixing raw SQL, start an explicit transaction with Database.BeginTransactionAsync, commit on success and let dispose roll back on failure. With a retrying execution strategy, wrap the whole unit in strategy.ExecuteAsync so it can be retried as a whole.
csharpawait using var tx = await db.Database.BeginTransactionAsync(); db.Accounts.Find(1)!.Balance -= 100; await db.SaveChangesAsync(); db.Accounts.Find(2)!.Balance += 100; await db.SaveChangesAsync(); await tx.CommitAsync();16 What are the inheritance mapping strategies?
mediumTable-per-hierarchy (TPH, the default) stores the whole hierarchy in one table with a discriminator column; it is fastest but has nullable columns. Table-per-type (TPT) uses a table per class joined on the key, which is normalised but slower to query. Table-per-concrete-type (TPC, added in EF Core 7) has a table per concrete class with no joins to the base and no shared table, with trade-offs for key generation and polymorphic queries.
17 How do you make EF Core queries faster in practice?
hardLook at the generated SQL (ToQueryString or logging) before guessing. Then: project only needed columns, use AsNoTracking for reads, avoid N+1 with Include or projection, page with Skip and Take on an ordered key, add indexes for filter and sort columns, batch writes with a single SaveChanges, use ExecuteUpdate for bulk changes, and use compiled queries (EF.CompileAsyncQuery) for hot paths. Measure before and after.
csharpConsole.WriteLine(db.Products.Where(p => p.Price > 100).ToQueryString()); var page = await db.Products.AsNoTracking() .OrderBy(p => p.Id).Skip(40).Take(20) .Select(p => new { p.Id, p.Name }).ToListAsync();
Frequently asked questions
Is EF Core slower than Dapper?
Dapper is leaner for simple queries, while EF Core adds tracking and translation overhead. With AsNoTracking, projections and compiled queries the gap is small for most applications.
What is the difference between Find and FirstOrDefault?
Find looks in the change tracker by primary key first and queries the database only if the entity is not already tracked; FirstOrDefault always queries.
Should I wrap DbContext in a repository?
DbContext already implements unit of work and repository-style access. Add a repository only if it hides something meaningful or helps testing.
Where does EF Core fit in the .NET stack?
It sits under controllers or minimal APIs; see ASP.NET Core MVC and .NET Core.
Related guides
More in Programming Language Interview Questions by Language
- Java 8 Streams and Lambdas Interview Questions
- Java Coding Interview Questions
- Java Collections Interview Questions
- Java Concurrency Utilities Interview Questions
- Java Exception Handling Interview Questions
- Java Garbage Collection Interview Questions
- Java Generics Interview Questions
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers
- Java Multithreading Interview Questions
- Java OOPs Interview Questions