Module 11 is the bridge between your C# code and the database. Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM) that allows you to interact with a database using C# objects, eliminating the need to write most of the SQL code manually.
An ORM (Object-Relational Mapper) is a layer that sits between your application and the database.
These are the two most important classes you will work with in EF Core.
DbContext: Think of this as the “Gateway” to your database. It manages the connection and tracks changes to your objects.DbSet<T>: Represents a specific table in the database. You use this to perform CRUD (Create, Read, Update, Delete) operations.C#
public class AppDbContext : DbContext {
public DbSet<Product> Products { get; set; } // This maps to a 'Products' table
}
There are two primary workflows for managing your data schema:
| Approach | Description | Use Case |
| Code First | You write C# classes first, and EF Core generates the database for you. | New projects; gives developers full control over the model in code. |
| Database First | You have an existing database, and EF Core generates C# classes based on it. | Legacy systems or when the database is managed by a separate DBA team. |
Since you are using Code First, what happens when you add a new property to your C# class? You use Migrations.
Add-Migration: EF Core looks at the changes in your C# code and creates a “script” (a C# file) to update the database.Update-Database: EF Core executes that script against your SQL server.In the real world, data is connected. EF Core handles three main types of relationships:
Category has many Products).User has one UserProfile).Student can have many Courses, and a Course has many Students). EF Core handles the “hidden” join table for you automatically.When you fetch a “Category” from the database, should it also fetch all 500 related “Products” automatically?
.Include() method.
_context.Categories.Include(c => c.Products).ToList();To build professional-grade apps, you must optimize your queries:
AsNoTracking(): Use this for “read-only” queries. It tells EF Core not to waste memory tracking changes to the objects.Where() while it’s still an IQueryable. This ensures the filtering happens inside the Database (SQL), not in your Application Memory (RAM).SELECT *). Only select the columns you actually need.By the end of this module, you will be able to: