Advertisement

Entity Framework Core & Data Access interview questions and answers

16 Entity Framework Core & Data Access interview questions for .NET roles, each with a model answer, examples and likely follow-ups.

16 questions
Advertisement

16 questions

Q11 Advanced Save

How do you implement soft deletes in EF Core using a global query filter?

A global query filter (HasQueryFilter in OnModelCreating) automatically applies a WHERE condition (like `IsDeleted == false`) to every query against a given entity type, without needing to remember to add that filter manually to every single LINQ query throughout the codebase -- implementing soft deletes (marking a row as deleted rather than physically removing it) transparently, while still allowing an explicit .IgnoreQueryFilters() call for the rare cases (like an admin 'view deleted items' feature) that need to see soft-deleted records.
public class Product { public bool IsDeleted { get; set; } }

modelBuilder.Entity<Product>().HasQueryFilter(p => !p.IsDeleted);

// Automatically excludes soft-deleted products from every query:
var products = await context.Products.ToListAsync();  // IsDeleted=true rows never appear

// Explicit override when needed:
var allIncludingDeleted = await context.Products.IgnoreQueryFilters().ToListAsync();
Real-world example
An e-commerce platform implements soft deletes for products (preserving order history references) using a global query filter, ensuring every part of the application automatically excludes deleted products without any developer needing to remember to add that condition manually.
Likely follow-ups
  • How do global query filters interact with navigation property includes?
  • What are the risks of forgetting a soft-delete filter exists when writing raw SQL alongside EF Core?
Data Types & Structures RESTful Web APIs & Controllers
Q12 Intermediate Save

What is the difference between First(OrDefault) and Single(OrDefault) in EF Core queries, and when should you use each?

First(OrDefault) returns the first matching element (or default if none/OrDefault variant) without requiring uniqueness, generating SQL with TOP 1/LIMIT 1 -- appropriate when you expect possibly multiple matches but only care about one. Single(OrDefault) throws an exception if more than one element matches, expressing the semantic guarantee that exactly one (or zero, for OrDefault) result is expected -- appropriate for lookups by unique key, where multiple matches would actually indicate a data integrity bug worth surfacing loudly rather than silently picking one.
// Appropriate when uniqueness isn't guaranteed or doesn't matter
var mostRecentOrder = await context.Orders.OrderByDescending(o => o.Date).FirstOrDefaultAsync();

// Appropriate when uniqueness IS expected and violations should be caught
var user = await context.Users.SingleOrDefaultAsync(u => u.Email == email);  // Email should be unique
Real-world example
A bug where a supposedly-unique email lookup was silently returning inconsistent results was caught immediately after switching from FirstOrDefault to SingleOrDefault, which threw an exception revealing a data integrity issue -- duplicate email rows that violated an assumed uniqueness constraint.
Likely follow-ups
  • What's the performance difference between First and Single at the SQL level?
  • Should Single always be preferred for queries with a unique index?
Exception Handling Data Types & Structures
Q13 Advanced Save

How does EF Core's compiled queries feature improve performance for frequently-executed queries, and when is it worth using?

EF Core normally caches the compiled internal representation of a LINQ query automatically based on its expression tree shape, but EF.CompileAsyncQuery explicitly pre-compiles a parameterized query once, bypassing some per-execution overhead (like expression tree comparison for cache lookup) for extremely hot, frequently-repeated queries -- generally only worth the added code complexity for queries executed an enormous number of times (like a high-throughput API's most critical hot path), since EF Core's automatic query caching already handles the vast majority of common scenarios well without manual compilation.
private static readonly Func<AppDbContext, int, Task<Product?>> _getProductById =
    EF.CompileAsyncQuery((AppDbContext context, int id) =>
        context.Products.FirstOrDefault(p => p.Id == id));

// Usage: skips some per-call query compilation overhead
var product = await _getProductById(context, productId);
Real-world example
A payment-processing hot path executed millions of times per day adopts a compiled query for its single most performance-critical lookup after profiling showed measurable query-compilation overhead at that specific extreme scale, while leaving all other, less frequently-hit queries as normal LINQ.
Likely follow-ups
  • What specific overhead does EF.CompileAsyncQuery actually eliminate?
  • Why isn't compiled queries recommended as a default practice for all queries?
Diagnostics & Performance CLR & Runtime
Q14 Intermediate Save

How do you configure and use raw SQL queries alongside LINQ in EF Core when a complex query is difficult or inefficient to express in LINQ?

FromSqlRaw/FromSqlInterpolated let you execute raw SQL that maps results to an entity type (composable with further LINQ operations like Where in some cases), while ExecuteSqlRawAsync/ExecuteSqlInterpolatedAsync execute raw SQL commands (like bulk updates) that don't return entities -- always use the interpolated or parameterized variants (never raw string concatenation) to avoid SQL injection vulnerabilities, reserving raw SQL for genuinely complex queries (recursive CTEs, database-specific functions) that LINQ can't cleanly express.
// Safe: parameterized via string interpolation (EF Core handles parameterization)
var minPrice = 100m;
var products = await context.Products
    .FromSqlInterpolated($"SELECT * FROM Products WHERE Price > {minPrice}")
    .ToListAsync();

// DANGEROUS: raw concatenation, vulnerable to SQL injection -- never do this
// FromSqlRaw($"SELECT * FROM Products WHERE Price > {minPrice}")
Real-world example
A reporting feature requiring a recursive CTE to compute a hierarchical category tree uses FromSqlInterpolated for that specific complex query, while every other simpler query in the application continues using standard LINQ.
Likely follow-ups
  • Why is FromSqlInterpolated safe from SQL injection despite looking like string interpolation?
  • When does raw SQL genuinely outperform an equivalent LINQ query?
Diagnostics & Performance Exception Handling
Q15 Beginner Save

What is a DbContext, and why should it generally not be shared across multiple concurrent operations?

DbContext represents a session with the database, tracking a unit of work's entities and managing the underlying database connection -- it's explicitly not thread-safe, meaning a single DbContext instance must not be used concurrently from multiple threads (like parallel Task.WhenAll calls sharing one context), which would corrupt its internal state; the standard pattern is one DbContext per unit of work (typically one per HTTP request in web apps, enforced naturally by its Scoped DI registration).
// WRONG: sharing one DbContext across concurrent operations
var tasks = ids.Select(id => context.Products.FindAsync(id));  // same context, concurrent access -- unsafe!
await Task.WhenAll(tasks);

// CORRECT: each operation gets its own context/scope, or operations run sequentially
foreach (var id in ids) {
    var product = await context.Products.FindAsync(id);
}
Real-world example
A bug causing intermittent, hard-to-reproduce data corruption is traced to a background job that incorrectly shared a single DbContext instance across multiple parallel Task.WhenAll operations, violating DbContext's fundamental single-threaded usage contract.
Likely follow-ups
  • What exception or symptom typically results from concurrent DbContext access?
  • How does DbContext's Scoped DI lifetime naturally enforce one-per-request usage?
Concurrency (asyncio/threading/multiprocessing) Dependency Injection
Q16 Advanced Save

What are the most important Entity Framework Core best practices for building performant, reliable data access code?

Key EF Core best practices include: using AsNoTracking() for read-only queries to skip unnecessary change-tracking overhead; projecting to only the specific columns actually needed rather than loading entire entities; preferring eager loading (Include()) over lazy loading in performance-sensitive paths to avoid the N+1 query problem, where accessing a related entity per row triggers a separate query for each one instead of a single combined query; wrapping multi-step writes in an explicit transaction to guarantee all-or-nothing consistency; and configuring connection pooling plus transient-fault retry logic (EnableRetryOnFailure()) for resilience against transient cloud database failures.
// Read-only, no change tracking
var users = dbContext.Users.AsNoTracking().ToList();

// Eager loading avoids N+1 queries
var usersWithOrders = dbContext.Users.Include(u => u.Orders).ToList();

// Explicit transaction for multi-step consistency
using var transaction = dbContext.Database.BeginTransaction();
try {
    dbContext.Users.Add(new User { Name = "John" });
    dbContext.SaveChanges();
    transaction.Commit();
} catch { transaction.Rollback(); }
Real-world example
A reporting page that was silently issuing hundreds of extra queries (one per row, via lazy-loaded related orders) is fixed by switching to eager loading with Include(), collapsing what had been an N+1 query pattern into a single efficient join, and adding AsNoTracking() since the page never modifies the data it displays.
Likely follow-ups
  • How do you detect an N+1 query problem in practice, given it isn't always obvious from the code alone?
  • What specific transient failures does EnableRetryOnFailure() protect against in a cloud-hosted database?
Entity Framework Core & Data Access SQL Queries

Showing 11–16 of 16