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.
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.
SaveChanges(), which writes all pending changes in one transaction. In ASP.NET Core it is scoped to the request.IQueryable<T>.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.
"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
DbContextis my session with the database: it holds the connection, tracks the entities I load, and when I callSaveChangesit works out the INSERT, UPDATE and DELETE statements and runs them in one transaction. EachDbSet<T>property is the entry point for one entity type, and because it implementsIQueryable<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 withToListAsync.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()orLogToin 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 toSqlBulkCopyor aSqlDataReader. The right answer is usually 'EF Core by default, drop down where you can measure the need.'"
| 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 |
db.Orders.Where(o => o.Total > 100): an expression tree, no SQL yet.Microsoft.Data.SqlClient) executes it; EF Core materialises rows into objects and, if tracking, snapshots them.| 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 |
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.
Checks that the candidate understands what EF Core actually does under the hood rather than just using it.
Green flags
DbContext is scoped and not thread-safeToQueryString() or loggingRed flags
DbContext as a singletonRelational 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.
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.
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.
DetectChanges, orders commands by dependencies, batches them (SQL Server default max batch size 42), wraps them in a transaction.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".
BlogContext, call ToQueryString() on three queries and read the SQL.optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information) and watch when commands actually execute.AsNoTracking, and Dapper using BenchmarkDotNet.Task.WhenAll and read the exception.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
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.ToList() early and filtering in memory. Why it is wrong: the whole table is downloaded. Instead: keep composing IQueryable until the final ToListAsync.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.ToQueryString(), LogTo and Application Insights.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.DbContext is not thread-safe. Instead: one context per unit of work, or a factory per parallel task.AsNoTracking() or project to DTOs.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 |
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.
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.
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.
Last updated 23 Nov 2026.