📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

What is Entity Framework Core? Explain what DbContext, DbSet and entities are, how a LINQ query becomes SQL, and when you would choose Dapper or plain ADO.NET instead.

Covers what EF Core is, the roles of DbContext, DbSet and entity classes, the LINQ-to-SQL translation pipeline, and how to choose between EF Core, Dapper and ADO.NET.

Beginner Theory Beginner ado-net dapper dbcontext ef-core linq orm

๐ŸŽฏ Key points

  • EF Core is an ORM that maps classes to tables and LINQ to SQL
  • DbContext = unit of work + change tracker + connection management, registered as scoped
  • DbSet<T> is the IQueryable entry point for one entity type
  • Deferred execution: SQL is generated and run only on enumeration (ToListAsync, FirstAsync)
  • Expression tree → query cache → provider SQL → parameterised command → materialised objects
  • See the SQL with ToQueryString(), LogTo and Application Insights dependency telemetry
  • Dapper for hand-tuned hot reads, ADO.NET/SqlBulkCopy for bulk and streaming
  • Mixing EF Core and Dapper: Dapper writes bypass the change tracker, so tracked entities go stale

โฑ 30-second answer

Entity Framework Core is Microsoft's object-relational mapper (ORM): you write C# classes (entities) and LINQ, and EF Core produces the SQL, runs it and turns the rows back into objects.

  • DbContext is a session with the database: it owns the connection, the change tracker and SaveChanges(), which writes all pending changes in one transaction. In ASP.NET Core it is scoped to the request.
  • DbSet is the entry point for querying and adding one entity type; it implements IQueryable<T>.
  • A LINQ query is captured as an expression tree, translated by the SQL Server provider into parameterised SQL, and executed only when you enumerate it (ToListAsync).

The trade-off: EF Core buys productivity, migrations and type safety; Dapper or ADO.NET buy you full control of the SQL for hot paths.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"EF Core is an object-relational mapper. I describe my domain as plain C# classes, the entities, and EF Core builds a model that maps them to tables, columns and foreign keys. The DbContext is my session with the database: it holds the connection, tracks the entities I load, and when I call SaveChanges it works out the INSERT, UPDATE and DELETE statements and runs them in one transaction. Each DbSet<T> property is the entry point for one entity type, and because it implements IQueryable<T>, a LINQ query against it is not run in memory. EF Core receives it as an expression tree, the SQL Server provider translates it to parameterised T-SQL, and nothing hits the database until I enumerate, for example with ToListAsync.

In ASP.NET Core I register the context with AddDbContext, which makes it scoped, so one request gets one context and one change tracker. It is not thread-safe, so I never share it across parallel tasks.

The mistake I see is treating EF Core as magic and never looking at the SQL. I use ToQueryString() or LogTo in development, and Application Insights dependency tracking in production. As for choice: EF Core is my default for line-of-business apps because of migrations, change tracking and safe parameterisation. For a hot read path with a hand-tuned query I am happy to use Dapper alongside it, and for streaming millions of rows I go down to SqlBulkCopy or a SqlDataReader. The right answer is usually 'EF Core by default, drop down where you can measure the need.'"


The building blocks

Piece What it is Notes
Entity A plain class mapped to a table Needs a key (convention: Id or <Type>Id)
DbContext Session: connection, model, change tracker, SaveChanges Scoped per request; not thread-safe
DbSet<T> IQueryable<T> over one entity type Also Add, Remove, Find
Model Metadata built from conventions, annotations and Fluent API Built once per context type and cached
Provider Microsoft.EntityFrameworkCore.SqlServer Translates expressions to T-SQL
Migrations C# files that evolve the schema dotnet ef migrations add

From LINQ to rows

  1. You compose db.Orders.Where(o => o.Total > 100): an expression tree, no SQL yet.
  2. On enumeration EF Core checks its query cache; on a miss it runs the query pipeline (normalise, translate, generate SQL).
  3. The SQL Server provider produces T-SQL with parameters for captured variables.
  4. ADO.NET (Microsoft.Data.SqlClient) executes it; EF Core materialises rows into objects and, if tracking, snapshots them.

EF Core vs Dapper vs ADO.NET

EF Core Dapper ADO.NET
You write LINQ SQL SQL + mapping code
Change tracking / migrations Yes No No
Overhead Low (a few ยตs per query when cached) Very low Lowest
Best for Most CRUD and domain logic Hot reads, complex reporting SQL Bulk copy, streaming, provider features

Production example

In a typical order API, EF Core handles all writes and most reads. One dashboard query with window functions was rewritten with Dapper after profiling showed EF Core's generated SQL was fine but the LINQ was unreadable; latency stayed at ~40 ms, but the query became reviewable by the DBA. EF Core's own overhead was never the bottleneck: missing indexes were.

๐Ÿ” What the interviewer is checking

Checks that the candidate understands what EF Core actually does under the hood rather than just using it.

Green flags

  • Explains deferred execution and translation to parameterised SQL
  • Knows DbContext is scoped and not thread-safe
  • Mentions inspecting SQL with ToQueryString() or logging
  • Gives a balanced view of Dapper and ADO.NET

Red flags

  • Thinks LINQ runs in memory against the table
  • Registers DbContext as a singleton
  • Dismisses EF Core as "too slow" without measurement

๐Ÿ“š Learn in depth

1. What an ORM solves

Relational databases store rows in tables joined by keys; C# works with object graphs and references. The gap (the object-relational impedance mismatch) covers identity, relationships, inheritance and change detection. EF Core closes it with a model: metadata describing every entity, property, key and relationship.

2. The model is built once

DbContext type โ”€โ”€โ–บ conventions โ”€โ”€โ–บ data annotations โ”€โ”€โ–บ OnModelCreating (Fluent API)
                                         โ”‚
                                         โ–ผ
                                  IModel (cached per context type)

The first DbContext instance pays to build the model (milliseconds to seconds for very large models); later instances reuse it. Compiled models (dotnet ef dbcontext optimize) remove this start-up cost.

3. The query pipeline

LINQ expression tree
   โ”‚  (parameter extraction: closure values become parameters)
   โ–ผ
query cache lookup โ”€โ”€ hit โ”€โ”€โ–บ cached executor
   โ”‚ miss
   โ–ผ
navigation expansion โ†’ translation to SQL expression tree โ†’ SQL generation
   โ–ผ
SqlCommand (parameterised) โ†’ SqlDataReader โ†’ shaper โ†’ entities

Because captured variables become parameters, the same query shape reuses both EF Core's cache and SQL Server's plan cache.

4. DbContext internals

  • StateManager / change tracker: a dictionary keyed by entity key, holding each tracked entity's state and an original-values snapshot.
  • Identity resolution: a tracking query returns the same instance for the same key within one context.
  • SaveChanges: calls DetectChanges, orders commands by dependencies, batches them (SQL Server default max batch size 42), wraps them in a transaction.
  • Connection: opened per operation and closed again, which works well with ADO.NET connection pooling.

5. Why scoped

The change tracker grows with every tracked entity and is not thread-safe. One context per request keeps memory bounded and avoids "A second operation was started on this context instance".

Try it yourself

  1. Create a console app with a BlogContext, call ToQueryString() on three queries and read the SQL.
  2. Add optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information) and watch when commands actually execute.
  3. Benchmark one query with EF Core tracking, EF Core AsNoTracking, and Dapper using BenchmarkDotNet.
  4. Run two queries in parallel on one context with Task.WhenAll and read the exception.

๐Ÿ’ป Code

A minimal EF Core 10 setup with SQL Server, registered in DI, and a query whose SQL you can inspect.

// Program.cs
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Connection string comes from configuration (user secrets locally, Key Vault in Azure)
builder.Services.AddDbContext<ShopDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));

var app = builder.Build();

app.MapGet("/orders/large", async (ShopDbContext db, CancellationToken ct) =>
    await db.Orders
        .AsNoTracking()                         // read-only: skip the change tracker
        .Where(o => o.Total > 100m)
        .OrderByDescending(o => o.PlacedAt)
        .Select(o => new OrderSummary(o.Id, o.Total, o.Customer.Name))
        .Take(20)
        .ToListAsync(ct));                      // SQL runs here, not before

app.Run();

public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Customer> Customers => Set<Customer>();
}

public sealed class Order
{
    public int Id { get; set; }
    public decimal Total { get; set; }
    public DateTimeOffset PlacedAt { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
}

public sealed class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
}

public sealed record OrderSummary(int Id, decimal Total, string CustomerName);

The SQL EF Core generates (simplified):

SELECT TOP(@p) [o].[Id], [o].[Total], [c].[Name]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[Total] > 100.0
ORDER BY [o].[PlacedAt] DESC

โš  Common mistakes

  • Mistake: Registering DbContext as a singleton. Why it is wrong: the change tracker grows forever and concurrent requests corrupt it. Instead: use AddDbContext (scoped) or AddDbContextFactory for background work.
  • Mistake: Calling ToList() early and filtering in memory. Why it is wrong: the whole table is downloaded. Instead: keep composing IQueryable until the final ToListAsync.
  • Mistake: Using synchronous ToList()/SaveChanges() in ASP.NET Core. Why it is wrong: each call blocks a ThreadPool thread for the whole database round trip, which causes ThreadPool starvation under load. Instead: ToListAsync(ct), SaveChangesAsync(ct) with the request's CancellationToken.
  • Mistake: Never looking at the generated SQL. Why it is wrong: N+1 queries and cartesian joins go unnoticed. Instead: use ToQueryString(), LogTo and Application Insights.
  • Mistake: Thinking EF Core is always slow and Dapper always fast. Why it is wrong: EF Core's overhead is microseconds; slow queries are usually bad SQL or missing indexes. Instead: measure with BenchmarkDotNet and execution plans.
  • Mistake: Updating rows with Dapper while the same DbContext still tracks them. Why it is wrong: the tracked copies are stale and a later SaveChanges can overwrite the Dapper change. Instead: use Dapper for reads, or share the connection and transaction (db.Database.GetDbConnection(), GetDbTransaction()) and reload or clear tracked entities after raw writes.
  • Mistake: Running parallel queries on one context. Why it is wrong: DbContext is not thread-safe. Instead: one context per unit of work, or a factory per parallel task.
  • Mistake: Tracking read-only queries. Why it is wrong: snapshots cost memory and CPU. Instead: AsNoTracking() or project to DTOs.

๐Ÿ› Senior insight: trade-offs

EF Core is a productivity tool with a well-defined cost: a cached query adds a few microseconds, a tracked entity costs a snapshot in memory. The senior move is not to pick a side in the ORM debate but to set a default (EF Core), make the SQL visible, and allow targeted escape hatches (Dapper, SqlQuery<T>, SqlBulkCopy) where profiling proves the need. When you mix them, keep one connection and transaction (GetDbConnection()/GetDbTransaction()), and remember that anything Dapper writes is invisible to the change tracker.

Visibility in production: the Application Insights SDK (or the Azure Monitor OpenTelemetry distro with SqlClient instrumentation) records every SqlClient call as a dependency with duration, target and, if you enable SQL text collection, the command text. Sort dependencies by duration and count per operation to spot slow queries and N+1 patterns; add TagWith("OrdersDashboard") so the query is recognisable in both telemetry and Query Store.

Option When it fits Cost When not to
EF Core CRUD, domain logic, migrations, most queries Learning LINQ translation; some overhead Bulk loads of millions of rows
Dapper Hand-tuned reads, reporting SQL No change tracking, no migrations, SQL in strings Complex write graphs
ADO.NET / SqlBulkCopy Bulk import, streaming, TVPs Most code Everyday CRUD

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions migrations. Why: Checks how the candidate takes schema changes to production.
    How to answer

    I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.

  2. When: Candidate says DbContext is not thread-safe. Why: Checks understanding of DbContext thread safety.
    How to answer

    A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.

  3. When: Candidate mentions the change tracker or SaveChanges. Why: Checks knowledge of change tracking and command ordering.
    How to answer

    SaveChanges asks the change tracker to run DetectChanges, which compares every tracked entity with its original-value snapshot and sets its state (Added, Modified, Deleted). EF Core then builds INSERT, UPDATE and DELETE commands, orders them by foreign-key dependencies (principals inserted before dependents, dependents deleted first), batches them (SQL Server batches up to 42 statements per round trip by default) and runs them inside one implicit transaction unless you already opened one. Generated values (identity, rowversion) are read back and key fix-up updates foreign keys and navigations. If an UPDATE or DELETE touches 0 rows because a concurrency token changed, EF Core throws DbUpdateConcurrencyException; any other database error rolls back the whole transaction and surfaces as DbUpdateException. SaveChangesAsync does the same work but awaits the network I/O, so request threads are not blocked; prefer it in ASP.NET Core.

โ†ฉ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me