Entity Framework Core — Complete Beginner Guide
Learning Objectives
- Explain what Entity Framework Core does
- Define model classes and a DbContext
- Create a database with migrations
- Query and save data with LINQ
- Perform basic CRUD operations safely
What Is Entity Framework Core
Entity Framework Core, often called EF Core, is an object relational mapper for .NET. It maps C# classes to database tables so you can query and save objects instead of writing every SQL statement by hand.
EF Core works with SQL Server, SQLite, PostgreSQL, MySQL, and more. For learning, SQLite keeps setup simple.
Installing Packages
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet tool install --global dotnet-ef
dotnet tool update --global dotnet-ef
The design package is also common in development scenarios:
dotnet add package Microsoft.EntityFrameworkCore.Design
Check your project file to confirm versions after installs.
Defining a Model
A model class represents a table conceptually.
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
}
By convention, Id becomes the primary key. Navigation properties can later express relationships such as one order containing many lines.
Creating the DbContext
The DbContext is your gateway to the database. It tracks changes and executes queries.
using Microsoft.EntityFrameworkCore;
public class LibraryContext : DbContext
{
public DbSet<Book> Books { get; set; }
public LibraryContext(DbContextOptions options) : base(options)
{
}
}
DbSet of Book exposes a queryable collection for that table.
Registering in Program.cs
builder.Services.AddDbContext(options =>
options.UseSqlite("Data Source=library.db"));
Configuration strings belong in appsettings or user secrets for real deployments rather than hard coded production values.
Creating a Migration
Migrations capture schema changes as code.
dotnet ef migrations add InitialCreate
dotnet ef database update
The first command generates migration files. The second applies them and creates or updates the database.
| Command | Effect |
|---|---|
| migrations add | Writes schema change code |
| database update | Applies pending migrations |
| migrations list | Shows migration history |
Querying Data
using (var db = contextFactory.Create())
{
List<Book> books = db.Books
.Where(b => b.Price < 100)
.OrderBy(b => b.Title)
.ToList();
foreach (var book in books)
{
Console.WriteLine(book.Title);
}
}
LINQ expressions are translated into SQL by EF Core when executed.
Finding by id
var one = db.Books.FirstOrDefault(b => b.Id == 1);
if (one is not null)
{
Console.WriteLine(one.Title);
}
Creating, Updating, and Deleting
// Create
var book = new Book { Title = "C sharp Basics", Author = "Sam", Price = 450 };
db.Books.Add(book);
db.SaveChanges();
// Update
book.Price = 399;
db.SaveChanges();
// Delete
db.Books.Remove(book);
db.SaveChanges();
SaveChanges pushes tracked modifications to the database in one call.
Change Tracking Basics
When you load an entity, EF Core tracks property changes. At SaveChanges it generates updates only for modified values. You can inspect states during debugging to learn what will be written.
Async Variants
var all = await db.Books.ToListAsync();
var found = await db.Books.FindAsync(1);
Prefer async methods in web applications so request threads are not blocked during database waits.
Common Mistakes
Forgetting SaveChanges
Add and Remove only stage changes until SaveChanges runs.
Querying huge tables into memory
Materialize carefully. Filter on the server with where before pulling endless rows.
Hardcoding connection strings
Use configuration layers so dev, test, and production can differ safely.
Ignoring migrations in team workflows
Treat migrations like source code. Review and apply them in a predictable order.
Key Takeaways
💡
- EF Core maps C# models to relational database tables
- A DbContext with DbSet members is your main data gateway
- migrations add writes schema changes; database update applies them
- LINQ queries translate to SQL and return tracked entities
- Stage changes with Add, Remove, or property edits, then call SaveChanges
Practice Questions
- What role does the DbContext play in an EF Core app?
- Which two commands create and apply an initial migration?
- Why is Id often treated as the primary key by convention?
- What must you call after Add or Remove to persist changes?
- Write a query that returns books ordered by price for titles shorter than forty characters.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions