Learn C# · 13/15

Entity Framework Core (Database Access)

8 min read

Course: C#
Difficulty: ⭐⭐⭐⭐☆ (It’s magic, until it breaks)


👋 Welcome to the Data Layer

Imagine a world where you have to write SELECT * FROM Users WHERE Id = 5 inside a string in your C# code. If you make a typo in that string (SLECT), the compiler won't tell you. You only find out when the app crashes in front of your boss. 😱

That was the dark age of ADO.NET (which still powers everything under the hood, by the way). But today, we are civilized. We use Entity Framework Core (EF Core).

EF Core is the glue that holds your beautiful C# classes and the cold, hard logic of a relational database together. By the end of this guide, you will be manipulating databases without writing a single line of SQL.


1. Intro to ORMs: Bridging Objects and Relational Databases

🧐 Definition

ORM (Object-Relational Mapper) is a technique (and software layer) that converts data between incompatible type systems using object-oriented programming languages.

⚠️ The Problem

In C#, you work with Objects (Classes, Inheritance, References).
In a Database (like SQL Server), you work with Tables (Rows, Columns, Foreign Keys).

These two worlds do not speak the same language. This is known as the impedance mismatch.

  • C# has a list inside an object (Order.Items).
  • Databases flatten everything; they need a separate table for Items joined by an ID.

Without an ORM, you have to manually map: "Take column 3 from the database row and put it into the Age property of the User object." It is tedious, error-prone, and boring.

💡 The Solution: EF Core

EF Core acts as a translator.

  1. You tell EF Core: context.Users.Add(newUser);
  2. EF Core translates this into: INSERT INTO Users (Name, Email) VALUES ('John', '[email protected]');
  3. EF Core sends it to the database.

Industry Reality: While EF Core is the standard, you might hear about "Dapper." Dapper is a "micro-ORM" that is faster but requires you to write your own SQL. EF Core is prioritized for productivity and complex relationships. Most companies use EF Core for 90% of operations and Dapper for the 10% that need extreme speed.

Fun Fact: EF Core is a complete rewrite of the old "Entity Framework 6". EF 6 was so heavy that people joked it had its own gravitational pull. EF Core is lightweight, modular, and cross-platform. 🚀


2. Setting up DbContext and Models (Code-First)

We are going to use the Code-First approach. This means we write C# classes first, and EF Core will generate the database tables for us.

🛠️ Installation

To get started, you need to install specific NuGet packages. In your terminal/command prompt inside your project folder:

bash
# Core framework
dotnet add package Microsoft.EntityFrameworkCore

# The specific provider for your DB (e.g., SQL Server)
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

# Tools to run commands like 'migrations'
dotnet add package Microsoft.EntityFrameworkCore.Tools

🏗️ The Models (POCOs)

Models are just standard C# classes. In the industry, we call them POCOs (Plain Old CLR Objects).

csharp
// Models/Product.cs
public class Product
{
    public int Id { get; set; } // EF Core automatically knows this is the Primary Key
    public string Name { get; set; }
    public decimal Price { get; set; }
    public bool IsInStock { get; set; }
}

🧠 The DbContext

The DbContext is the heart of EF Core. It represents a session with the database and creates a bridge between your code and the DB.

Think of DbContext as the Librarian. You ask the Librarian for books (Data), the Librarian knows exactly which shelf (Table) to look at, and ensures you check them out correctly (Transactions).

csharp
using Microsoft.EntityFrameworkCore;

// Data/AppDbContext.cs
public class AppDbContext : DbContext
{
    // This property tells EF Core: "I want a table named 'Products' based on the 'Product' class"
    public DbSet<Product> Products { get; set; }

    // Configuration (In real apps, connection strings go in appsettings.json!)
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // We are using LocalDB for this example (Built into Visual Studio)
        optionsBuilder.UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=MyFreeCodeCampDb;Trusted_Connection=True;"
        );
    }
}

Common Pitfall: Never hardcode connection strings (passwords) in production code! Use IConfiguration and User Secrets.


3. CRUD Operations: Create, Read, Update, Delete

Now that we have the setup, let's manipulate data. We will use LINQ (Language Integrated Query) to talk to the DB.

Important Rule: Always use async/await with database operations (SaveChangesAsync, ToListAsync). Database calls are I/O bound; blocking the thread while waiting for the database is a performance crime. 🚔

Assume we have an instance of our context:
using var context = new AppDbContext();

C - Create

csharp
public async Task AddProductAsync()
{
    var newProduct = new Product 
    { 
        Name = "Mechanical Keyboard", 
        Price = 99.99m, 
        IsInStock = true 
    };

    // 1. Add to the DbSet (State becomes "Added")
    await context.Products.AddAsync(newProduct);

    // 2. Commit changes to the actual database
    await context.SaveChangesAsync(); 
    
    // Fun fact: After SaveChanges, newProduct.Id will be populated with the generated ID!
    Console.WriteLine($"Created Product with ID: {newProduct.Id}");
}

R - Read

EF Core uses LINQ to generate SQL queries.

csharp
public async Task GetCheapProductsAsync()
{
    // This does NOT fetch all data yet. It builds the query expression.
    var cheapProducts = await context.Products
        .Where(p => p.Price < 50)
        .OrderBy(p => p.Name)
        .ToListAsync(); // execution happens HERE
        
    foreach(var p in cheapProducts)
    {
        Console.WriteLine(p.Name);
    }
}

Performance Tip (Industry Standard): If you are just reading data to display it and not modifying it, use .AsNoTracking().

csharp
var viewData = await context.Products.AsNoTracking().ToListAsync();

This tells EF Core: "Don't bother taking a snapshot of these objects to detect changes." It is significantly faster.

U - Update

EF Core has a "Change Tracker." It watches the objects you retrieve.

csharp
public async Task UpdatePriceAsync(int productId, decimal newPrice)
{
    // 1. Retrieve the entity
    var product = await context.Products.FindAsync(productId);

    if (product != null)
    {
        // 2. Modify the property
        product.Price = newPrice; 

        // 3. Save. EF Core noticed you changed 'Price' and writes the SQL UPDATE automatically.
        await context.SaveChangesAsync();
    }
}

D - Delete

csharp
public async Task DeleteProductAsync(int productId)
{
    var product = await context.Products.FindAsync(productId);
    
    if (product != null)
    {
        // Mark as Deleted
        context.Products.Remove(product);
        
        // Commit
        await context.SaveChangesAsync();
    }
}

4. Migrations: Managing Database Schema Changes

🧐 Definition

Migrations are version control for your database schema.

⚠️ The Problem

You created the Product class with Name and Price. You ran the app, and the database table was created.
Two weeks later, your boss says: "We need a Description field."
You add public string Description { get; set; } to your class.

CRASH. 💥
The code expects a Description column, but the database table doesn't have one.

💡 The Solution: Migrations

Migrations allow you to evolve your database schema alongside your code without losing the data currently in the database.

How to use Migrations (CLI)

Step 1: Create the Migration
Open your terminal in the project folder.

bash
dotnet ef migrations add AddDescriptionToProduct

What happens: EF Core compares your C# classes with the current state of the database. It sees you added Description. It generates a C# file in a Migrations folder with instructions on how to apply (Up) and revert (Down) this change.

Step 2: Apply the Migration

bash
dotnet ef database update

What happens: EF Core looks at the migration file and applies the SQL command (ALTER TABLE Products ADD Description...) to your actual database.

Step 3: Oops? Revert it.
If you made a mistake (and haven't pushed to production yet), you can undo the last apply:

bash
dotnet ef database update LastGoodMigrationName

Imagination Time: Think of Migrations like "Save Points" in a video game. Before you fight the boss (deploy to production), you create a save point. If the boss kills you (bugs), you can reload the save.

☠️ The "EnsureCreated" Trap

You might see tutorials use context.Database.EnsureCreated().
Do not use this in real projects. It creates the DB but bypasses migrations. Once you use it, you can't easily switch to using Migrations later. It is for prototypes only.


🧪 Interesting Simulation: The "N+1" Problem

This is the most common interview question regarding ORMs.

Scenario: You have Authors and Books.

csharp
var authors = context.Authors.ToList(); // 1 Query: SELECT * FROM Authors
foreach (var author in authors)
{
    Console.WriteLine(author.Books.Count); // N Queries: SELECT * FROM Books WHERE AuthorId = ?
}

If you have 1000 authors, you just ran 1001 database queries. Your Database Administrator (DBA) will hunt you down. 🏃‍♂️💨

Fix: Eager Loading with .Include()

csharp
var authors = context.Authors
    .Include(a => a.Books) // Joins the data in the initial query
    .ToList();

Now it is just 1 Query (or 2 optimized ones).


📚 Resources & References


🧠 Checkpoint

  • ORM: Translates C# to SQL.
  • DbContext: The gateway/session.
  • Code-First: C# Classes define the DB structure.
  • Migrations: How we update the DB structure safely.
  • AsNoTracking: The fast lane for reading data.

Next up, you would usually learn about Relationships (One-to-One, One-to-Many), but for now, go create a database without writing SQL and feel the power! ⚡

Challenge

Challenge: Implement an EF Core Book Repository

You are tasked with implementing a data repository for managing books and authors using Entity Framework Core. You have been provided with Author and Book models, a BookStoreContext for database interaction, and an IBookRepository interface.

Your goal is to complete the BookRepository class by implementing its five methods. Adhere to EF Core best practices for asynchronous operations, performance, and data integrity.

Requirements:

  1. GetPublishedBooksWithAuthorsAsync(): This method should fetch all books where IsPublished is true. To prevent the N+1 problem, you must load the associated Author for each book in a single database query.
  2. FindBooksByAuthorNameAsync(string authorName): This method should retrieve all books written by an author with the specified name. Since this is a read-only operation, it must be optimized for performance by disabling change tracking.
  3. AddNewBookForAuthorAsync(int authorId, Book newBook): This method must associate the provided newBook object with the author specified by authorId and then add the new book to the database.
  4. UpdateBookPriceAsync(int bookId, decimal newPrice): Find the book with the given bookId, update its Price property to newPrice, and persist the change. The method should return true if the book was found and updated, and false otherwise.
  5. DeleteBookAsync(int bookId): Find the book with the given bookId and permanently remove it from the database. The method should return true if the book was found and deleted, and false otherwise.

All database interactions must be performed asynchronously using the async/await pattern.

Expected result

Your code should provide a complete implementation of the BookRepository class that correctly fulfills all requirements of the IBookRepository interface.

  • The GetPublishedBooksWithAuthorsAsync method must use .Include(b => b.Author) and .Where(b => b.IsPublished) before asynchronously converting the result to a list.
  • The FindBooksByAuthorNameAsync method must use .Where(b => b.Author.Name == authorName) and chain .AsNoTracking() to the query for performance.
  • The AddNewBookForAuthorAsync method must set the AuthorId on the new book object, call _context.Books.AddAsync(newBook), and then await _context.SaveChangesAsync().
  • The UpdateBookPriceAsync and DeleteBookAsync methods must first retrieve the target book entity (e.g., using FirstOrDefaultAsync). If the entity is found, they should perform the respective update or remove operation and then call await _context.SaveChangesAsync(), returning true. If the entity is not found, they should return false without calling SaveChangesAsync.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.