C# Entity Framework Cheat Sheet
Covers Entity Framework Core basics: DbContext, DbSet, CRUD operations, eager loading with Include, and managing schema migrations from the CLI.
2 PagesIntermediateMar 28, 2026
DbContext & Model
Defining entities and the database session type.
csharp
public class Blog{ public int Id { get; set; } public string Title { get; set; } = string.Empty; public List<Post> Posts { get; set; } = new();}public class AppDbContext : DbContext{ public DbSet<Blog> Blogs => Set<Blog>(); public DbSet<Post> Posts => Set<Post>(); protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer("Server=.;Database=BlogDb;Trusted_Connection=True;");}
CRUD Operations
Creating, reading, updating, and deleting entities.
csharp
using var db = new AppDbContext();// Createdb.Blogs.Add(new Blog { Title = "My Blog" });await db.SaveChangesAsync();// Readvar blog = await db.Blogs.FirstOrDefaultAsync(b => b.Title == "My Blog");var all = await db.Blogs.Include(b => b.Posts).ToListAsync(); // Eager load related data// Updateblog!.Title = "Updated Title";await db.SaveChangesAsync();// Deletedb.Blogs.Remove(blog);await db.SaveChangesAsync();
Migrations (CLI)
Versioning the database schema from your model.
bash
dotnet tool install --global dotnet-ef # Install the EF Core CLI tooldotnet ef migrations add InitialCreate # Generate a migration from model changesdotnet ef database update # Apply pending migrations to the databasedotnet ef migrations remove # Remove the last unapplied migration
Key Concepts
Core EF Core building blocks.
- DbContext- Represents a session with the database; tracks entity changes for SaveChanges()
- DbSet<T>- Represents a table/collection queried and modified via the context
- Change tracking- EF tracks entity state (Added, Modified, Deleted, Unchanged) automatically
- Include / ThenInclude- Eagerly load related navigation properties in a single query
- Lazy loading- Related data loaded on first access when navigation properties are virtual and enabled
- Migrations- Code-first schema versioning generated from model changes
- AsNoTracking()- Skips change tracking for read-only queries, improving performance
Pro Tip
Use .AsNoTracking() on read-only queries such as API GET endpoints — it avoids the overhead of EF's change tracker and can noticeably speed up large result sets.
Was this cheat sheet helpful?
Explore Topics
#CEntityFramework#CEntityFrameworkCheatSheet#Programming#Intermediate#DbContextModel#CRUDOperations#MigrationsCLI#KeyConcepts#Databases#CommandLine#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance