Entity Framework (EF6 & EF Core)
Setup
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 ModelsEntity 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.