This EF Core interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.
1. What is Entity Framework Core?
Answer: Entity Framework Core is a cross-platform object-relational mapper (ORM) for .NET. It lets developers work with database data through .NET entity classes and LINQ while translating supported queries into SQL. EF Core also provides change tracking, relationships, migrations and transaction integration. It does not eliminate the need to understand SQL or inspect generated queries when performance matters.
Example
var activeCustomers = await db.Customers
.Where(c => c.IsActive)
.ToListAsync();
2. What is DbContext and what is its recommended lifetime?
Answer: DbContext represents a unit of work with a database. It manages entity tracking, database connections and saving changes. In a typical web application, register it as scoped so one context is used for one request or unit of work. A DbContext is not thread-safe; do not run multiple parallel operations on the same instance.
Example
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));
3. What is DbSet in EF Core?
Answer: DbSet<T> represents a queryable collection of entities of type T and is commonly used as the starting point for queries and changes. It is not simply an in-memory list: LINQ expressions are translated by the provider when executed. A DbSet also supports adding, updating and removing entities that will be persisted when SaveChanges is called.
Example
public DbSet<Order> Orders => Set<Order>();
var pending = await db.Orders.Where(o => o.Status == "Pending").ToListAsync();
4. What is change tracking in EF Core?
Answer: When an entity is tracked, EF Core stores its original values and monitors changes. Calling SaveChanges generates the appropriate INSERT, UPDATE or DELETE statements. Tracking is useful when you intend to edit entities. For read-only queries, tracking may add unnecessary memory and CPU overhead, so consider AsNoTracking or a projection.
Example
var order = await db.Orders.FindAsync(id);
order!.Status = "Approved";
await db.SaveChangesAsync();
5. What is the difference between AsNoTracking and AsTracking?
Answer: AsNoTracking tells EF Core not to track entities returned by a query, which is usually more efficient for read-only work. AsTracking explicitly enables tracking. A no-tracking query returns entity instances that can still be changed in memory, but those changes are not automatically detected and saved by that DbContext. Use tracking when the unit of work will modify the entities.
Example
var rows = await db.Products
.AsNoTracking()
.Where(p => p.IsPublished)
.Select(p => new ProductListItem(p.Id, p.Name))
.ToListAsync();
6. What are EF Core migrations?
Answer: Migrations are versioned changes that describe how the database schema should evolve with the model. They allow a team to create, review and apply schema changes over time. Generate migrations during development, inspect the generated operations and deploy them through a controlled release process. Avoid blindly applying migrations at application startup in production where multiple instances or restricted permissions may create deployment risks.
Example
dotnet ef migrations add AddOrderStatus
dotnet ef database update
7. What are eager, lazy and explicit loading?
Answer: Eager loading retrieves related data as part of the initial query, commonly using Include. Lazy loading retrieves a navigation property when it is accessed, if lazy-loading proxies or another supported mechanism is configured. Explicit loading requests related data deliberately through the entry API. Eager loading is predictable; lazy loading can cause unexpected extra queries; explicit loading gives control when only selected relationships are needed.
Example
// Eager loading
var orders = await db.Orders.Include(o => o.Customer).ToListAsync();
// Explicit loading
await db.Entry(order).Reference(o => o.Customer).LoadAsync();
8. What is the N+1 query problem?
Answer: The N+1 problem occurs when an application executes one query to load a set of parent records and then executes another query for each parent to load related data. The number of database round trips grows with the number of parents. It often appears with lazy loading or loops that issue queries. Use projection, Include or deliberate batching, then inspect SQL and query counts to verify the fix.
Example
// Avoid querying the database inside a loop.
var rows = await db.Orders
.Select(o => new { o.Id, CustomerName = o.Customer.Name })
.ToListAsync();
9. How do Include and ThenInclude work?
Answer: Include requests a related navigation property to be loaded with the root query. ThenInclude continues from a previously included navigation to load a nested relationship. Include only the relationships you need; loading a large graph can create duplicate data, large joins and memory pressure. For API responses, a DTO projection is often more efficient than returning full entity graphs.
Example
var orders = await db.Orders
.Include(o => o.Customer)
.Include(o => o.Items).ThenInclude(i => i.Product)
.ToListAsync();
10. What is projection in EF Core and why use Select?
Answer: Projection selects only the fields needed for the result, often into a DTO or anonymous type. It reduces data transferred from the database and avoids materialising full entity graphs when the application only needs a few columns. Projection is especially useful for list pages and read APIs. Keep the projection expression translatable by the provider.
Example
var result = await db.Employees
.Select(e => new EmployeeDto(e.Id, e.Name, e.Department.Name))
.ToListAsync();
11. What is client evaluation versus server evaluation?
Answer: Server evaluation means EF Core translates part of the LINQ expression into SQL and the database performs the operation. Client evaluation means .NET code executes after data has been retrieved. EF Core generally throws when an untranslatable expression appears in a query filter or other non-top-level part, rather than silently downloading the entire table. Keep filters and joins translatable, or deliberately materialise a suitably limited result before client processing.
Example
// Database filter first; small result is then processed in .NET.
var names = await db.Customers
.Where(c => c.IsActive)
.Select(c => c.Name)
.ToListAsync();
var formatted = names.Select(FormatName).ToList();
12. How do you manage transactions in EF Core?
Answer: A single SaveChanges call is normally transactional when the provider supports transactions: either its changes succeed together or they are rolled back. Use an explicit transaction when a business operation spans multiple SaveChanges calls or combines EF operations with other commands that must commit together. Keep transactions short and consider retry strategies and execution strategies when using transient-fault handling.
Example
await using var tx = await db.Database.BeginTransactionAsync();
await db.Orders.AddAsync(order);
await db.SaveChangesAsync();
await db.AuditLogs.AddAsync(log);
await db.SaveChangesAsync();
await tx.CommitAsync();
13. What is optimistic concurrency in EF Core?
Answer: Optimistic concurrency assumes conflicts are uncommon and checks whether a row changed since it was read. Configure a concurrency token such as a SQL Server rowversion. When an update affects no row because the token no longer matches, EF Core throws DbUpdateConcurrencyException. The application can then reload, merge or ask the user to resolve the conflict rather than silently overwriting another update.
Example
public class Product
{
public int Id { get; set; }
[Timestamp] public byte[] RowVersion { get; set; } = [];
}
14. How do you configure one-to-many and many-to-many relationships?
Answer: A one-to-many relationship has a principal entity and dependent entities with a foreign key. A many-to-many relationship lets each side relate to multiple rows on the other side; EF Core can manage a join table automatically for simple cases, or you can model the join entity explicitly when it has additional fields. Configure relationships with conventions, attributes or Fluent API depending on complexity.
Example
modelBuilder.Entity<Order>()
.HasMany(o => o.Items)
.WithOne(i => i.Order)
.HasForeignKey(i => i.OrderId);
15. How do you configure keys and indexes in EF Core?
Answer: A primary key uniquely identifies an entity. EF Core discovers common key conventions such as Id or EntityNameId, while Fluent API can configure composite or alternate keys. Indexes help the database find rows efficiently but add storage and write overhead. Create indexes to support actual filters, joins and ordering; validate them against execution plans and workload patterns.
Example
modelBuilder.Entity<Employee>()
.HasIndex(e => new { e.DepartmentId, e.LastName });
modelBuilder.Entity<Employee>()
.HasAlternateKey(e => e.EmployeeCode);
16. How can you execute raw SQL safely with EF Core?
Answer: Use parameterised APIs such as FromSql or ExecuteSql with interpolated values so user input is parameterised. Avoid concatenating untrusted text into SQL strings. Raw SQL can be useful for database-specific queries or commands, but it should be an intentional choice and tested against the configured provider. Use a keyless entity type for result sets that do not map to a tracked table entity.
Example
var customer = await db.Customers
.FromSql($"SELECT * FROM Customers WHERE Id = {customerId}")
.SingleOrDefaultAsync();
17. What is the difference between SaveChanges and SaveChangesAsync?
Answer: Both persist tracked changes. SaveChanges performs synchronous database I/O and blocks the calling thread while waiting. SaveChangesAsync awaits the provider’s asynchronous I/O, allowing the thread to serve other work while waiting. In web applications, use async consistently for I/O-bound database calls and await the result. Do not call both methods concurrently on the same DbContext.
Example
db.Orders.Add(order);
await db.SaveChangesAsync(cancellationToken);
18. What is split query behaviour in EF Core?
Answer: When loading multiple collection navigations in one query, joins can multiply result rows and repeat parent data. Split queries issue more than one SQL query to load the graph in parts, which can reduce row duplication but increases database round trips and may have consistency considerations between queries. Use AsSplitQuery when measurements show a large single-query graph is inefficient; compare both behaviours with realistic data.
Example
var blogs = await db.Blogs
.Include(b => b.Posts)
.Include(b => b.Contributors)
.AsSplitQuery()
.ToListAsync();
19. How do you improve EF Core query performance?
Answer: Project only required columns, filter and paginate at the database, use no-tracking for read-only results, avoid N+1 patterns and inspect generated SQL. Ensure indexes support the query and avoid loading huge graphs. Use asynchronous I/O for database calls and measure with realistic data and execution plans. Do not assume that adding Include, compiling a query or adding an index automatically makes every query faster.
Example
var page = await db.Orders
.AsNoTracking()
.Where(o => o.CreatedAt >= fromDate)
.OrderByDescending(o => o.CreatedAt)
.Select(o => new OrderRow(o.Id, o.CreatedAt, o.Total))
.Take(50)
.ToListAsync();
20. Can EF Core perform bulk updates and deletes?
Answer: EF Core supports set-based operations such as ExecuteUpdate and ExecuteDelete in modern versions, allowing the database to update or delete matching rows without loading each entity into the change tracker. These operations bypass normal per-entity change tracking and SaveChanges hooks, so use them carefully when application logic depends on tracked entity events or concurrency behaviour. For older versions, use suitable provider capabilities or a carefully designed SQL command.
Example
await db.Products
.Where(p => !p.IsActive)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.IsArchived, true));
How to prepare for your interview
Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.
Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.
Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.