Roadmap › 1. .NET › Step 15
EF

Entity Framework (EF6 & EF Core)

DbContext, code-first and database-first, conventions and Fluent API, relationships, migrations, querying and loading strategies, change tracking, concurrency, transactions, performance tuning and EF6 vs EF Core.
Quick revision for interview day. Print it or save it as a PDF.

Setup

bash
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install -g dotnet-ef
dotnet ef migrations add Init
dotnet ef database update
dotnet ef migrations script --idempotent -o deploy.sql
dotnet ef dbcontext scaffold "<conn>" Microsoft.EntityFrameworkCore.SqlServer -o Models

Entity states

Detached · Added → INSERT · Unchanged · Modified → UPDATE · Deleted → DELETE.

Loading

Include/ThenInclude (eager) · Entry().Collection().Load() (explicit) · lazy proxies (avoid) · Select projection (best for reads) · AsSplitQuery.

Query tips

AsNoTracking · Select DTOs · AnyAsync · paginate Skip/Take · ToQueryString() · FromSql($"") · SqlQuery<T> · ExecuteUpdate/Delete · EF.CompileAsyncQuery · IgnoreQueryFilters.

Configuration precedence

Fluent API > Data Annotations > Conventions. Use IEntityTypeConfiguration<T>.

Relationships

HasOne().WithMany().HasForeignKey().OnDelete() · HasOne().WithOne().HasForeignKey<T>() · many-to-many via skip navigations · owned/complex types · TPH (default) / TPT / TPC.

Concurrency & transactions

[Timestamp] byte[] RowVersion → DbUpdateConcurrencyException → 409 · SaveChanges = one transaction · BeginTransactionAsync for multiple saves · execution strategy with retries.

DbContext rules

Scoped · short-lived · not thread-safe · IDbContextFactory for background/parallel · AddDbContextPool for throughput.