Learn ASP.NET Core Β· 5/13

Data Access with Entity Framework Core

6 min read

Course: ASP.NET Core

Topic: Data Access with Entity Framework Core


1. Introduction to EF Core: Bridging Objects and Relational Data

Definition:
Entity Framework Core (EF Core) is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology. It acts as an Object-Relational Mapper (ORM).

The Problem: The Impedance Mismatch 🧩
Imagine you are building a house (your software) using LEGO bricks (C# Objects). But, you are required to store these LEGO bricks in flat spreadsheets (Relational Database Tables) every night.

To save your work, you have to take apart your beautiful 3D LEGO castle and list every single brick in a row-and-column Excel sheet. When you want to play again, you have to read the sheet, find the bricks, and rebuild the castle from scratch.

  • C# speaks in Objects, Inheritance, and Lists.
  • SQL speaks in Tables, Rows, and Foreign Keys.
    Translating between them manually (writing raw ADO.NET code) is tedious, error-prone, and feels like churning butter by hand in the age of electricity.

The Solution: The EF Core Bridge πŸŒ‰
EF Core acts as a highly intelligent translator. You interact only with your C# objects (LEGOs), and EF Core automatically handles the "flattening" into SQL commands and the "rebuilding" back into objects. It enables you to work with data using .NET objects, eliminating the need for most of the data-access code you usually need to write.

Did you know? 🧠
Early ORMs were so slow that developers called them "Object-Relational Vietnamese War" because it was a quagmire no one wanted to enter. Today, EF Core (especially .NET 8+) performs nearly as fast as raw SQL (Dapper) for many read operations due to compiled query caches!


2. Defining the Domain: Creating Entities and the DbContext

To start using EF Core, we need to map our "World" (Domain) to the database.

The Alphabet: Entities (POCOs)
Entities are just normal C# classes. We often call them POCOs (Plain Old CLR Objects). They represent a table in your database.

Example Scenario: A Blogging Platform.

csharp
// Models/Blog.cs
public class Blog
{
    public int Id { get; set; } // EF Core recognizes 'Id' as Primary Key by convention
    public string Url { get; set; }
    
    // Navigation Property: A Blog has many Posts
    public List<Post> Posts { get; set; } = new(); 
}

// Models/Post.cs
public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    // Foreign Key mapping
    public int BlogId { get; set; }
    
    // Navigation Property: A Post belongs to one Blog
    public Blog Blog { get; set; } 
}

The Word: DbContext (The Gateway)
The DbContext is the heart of EF Core. It represents a session with the database. It manages connections, tracks changes to your objects, and creates the "SQL" for you.

Industry Standard Pattern: Separate Configuration πŸ—οΈ
Do not clutter your OnModelCreating method with hundreds of lines of configuration. Use IEntityTypeConfiguration<T>.

1. Define Configuration:

csharp
// Data/Configurations/BlogConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public class BlogConfiguration : IEntityTypeConfiguration<Blog>
{
    public void Configure(EntityTypeBuilder<Blog> builder)
    {
        builder.HasKey(b => b.Id);
        
        builder.Property(b => b.Url)
            .IsRequired()
            .HasMaxLength(200);

        // Explicitly defining the relationship (good practice)
        builder.HasMany(b => b.Posts)
            .WithOne(p => p.Blog)
            .HasForeignKey(p => p.BlogId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

2. The DbContext:

csharp
// Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Scans the assembly for all classes implementing IEntityTypeConfiguration
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

3. Registration (Program.cs):
Strictly following .NET 8+ standards:

csharp
// Program.cs
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Get Connection String from appsettings.json
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

// Register DbContext
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

3. Code-First Migrations: Version Controlling Your Database

The Problem: Schema Evolution πŸ¦•
Your code changes. You added a Rating property to the Post class. Now your C# code and your SQL Database are out of sync. The application crashes because the database table Posts doesn't have a Rating column.

The Solution: Migrations ⏳
Migrations are like "Git commits" for your database. They record changes to your model over time and can apply (or revert) those changes to the database schema.

Step-by-Step Industry Flow:

  1. Install Tools (One-time setup):
    Ensure you have the global tool installed.

    bash
    dotnet tool install --global dotnet-ef

    Note: If already installed, update it: dotnet tool update --global dotnet-ef

  2. Add Required Package:

    bash
    dotnet add package Microsoft.EntityFrameworkCore.Design
  3. Create a Migration:
    This looks at your AppDbContext and compares it to the last snapshot.

    bash
    dotnet ef migrations add InitialCreate

    Output: A folder Migrations is created with C# files describing the table creation.

  4. Update the Database:
    This translates the migration C# code into SQL and runs it against the database.

    bash
    dotnet ef database update

Imagination Time ☁️
Think of dotnet ef migrations add as packing your bags for a trip (preparing the changes), and dotnet ef database update as actually getting on the plane (applying them). You can pack your bags multiple times (add migrations) before you actually travel!


4. Practical Data: Performing CRUD Operations with LINQ

Concept: The Unit of Work
All changes happen in memory first. Nothing touches the database until you call SaveChangesAsync(). This allows you to batch multiple operations into a single transaction efficiently.

1. Create (Insert) 🌱

csharp
public async Task CreateBlogAsync(AppDbContext context)
{
    var newBlog = new Blog { Url = "https://freecodecamp.org" };
    
    // State: Added (EF starts tracking this object)
    await context.Blogs.AddAsync(newBlog); 
    
    // Generates: INSERT INTO Blogs (Url) VALUES (...)
    await context.SaveChangesAsync(); 
}

2. Read (Select) πŸ”
We use LINQ (Language Integrated Query). It allows us to write query logic in C# that compiles to SQL.

  • AsNoTracking(): Pro Tip! Use this for read-only lists. It tells EF Core not to track changes, making it much faster.
csharp
public async Task<List<Blog>> GetBlogsAsync(AppDbContext context)
{
    // Generates: SELECT * FROM Blogs WHERE Url LIKE '%google%'
    return await context.Blogs
        .AsNoTracking() // Performance boost for reads
        .Where(b => b.Url.Contains("google"))
        .ToListAsync();
}

3. Update (Modify) πŸ› οΈ
EF Core has "Change Tracking". You fetch it, change it, and save it. EF Core detects the difference.

csharp
public async Task UpdateBlogUrlAsync(AppDbContext context, int id)
{
    // 1. Fetch
    var blog = await context.Blogs.FindAsync(id);
    
    if (blog != null)
    {
        // 2. Modify (State changes to Modified)
        blog.Url = "https://updated-url.com";
        
        // 3. Save (Generates UPDATE SQL for changed columns only)
        await context.SaveChangesAsync();
    }
}

4. Delete (Remove) πŸ—‘οΈ

csharp
public async Task DeleteBlogAsync(AppDbContext context, int id)
{
    var blog = await context.Blogs.FindAsync(id);
    
    if (blog != null)
    {
        // State: Deleted
        context.Blogs.Remove(blog);
        
        // Generates: DELETE FROM Blogs WHERE Id = ...
        await context.SaveChangesAsync();
    }
}

5. Essential Best Practices (Don't skip this! ⚠️)

  1. Always use Async: Database I/O is slow. Using ToListAsync (instead of ToList) prevents your server from freezing while waiting for data.
  2. Filter Early: Do your Where() logic before calling ToList(). If you do ToList().Where(...), you pull the entire database table into memory and filter it there. That is a disaster for performance.
  3. Use Projections (Select): Don't fetch columns you don't need.
    csharp
    // Good: Only fetches Url
    var urls = await context.Blogs.Select(b => b.Url).ToListAsync();

πŸ“š References & Further Reading

Challenge

You are tasked with building the data access layer for a new library application using Entity Framework Core. Your goal is to define the data model, configure it using the Fluent API, set up the DbContext, and implement an optimized data retrieval method.

Requirements:

  1. Define Entities:

    • Create a public C# class named Author with the following properties:
      • Id (int)
      • Name (string)
      • A collection navigation property for related books, named Books (e.g., ICollection<Book>).
    • Create a public C# class named Book with the following properties:
      • Id (int)
      • Title (string)
      • PublishedYear (int)
      • The foreign key AuthorId (int).
      • A reference navigation property to its Author.
  2. Create Entity Configurations:

    • Create a class AuthorConfiguration that implements IEntityTypeConfiguration<Author>.
      • Configure Id as the primary key.
      • Configure the Name property to be required and have a maximum length of 150 characters.
      • Configure the one-to-many relationship with Book, specifying that deleting an Author should also delete all their associated Book entities (DeleteBehavior.Cascade).
    • Create a class BookConfiguration that implements IEntityTypeConfiguration<Book>.
      • Configure Id as the primary key.
      • Configure the Title property to be required.
      • Configure the many-to-one relationship back to Author using the AuthorId foreign key.
  3. Create the DbContext:

    • Create a class LibraryDbContext that inherits from DbContext.
    • Add DbSet<Author> and DbSet<Book> properties named Authors and Books respectively.
    • Override the OnModelCreating method to apply both the AuthorConfiguration and BookConfiguration you created.
  4. Implement the Data Service Method:

    • Complete the GetAuthorsWithRecentBooksAsync method within the provided BookService class.
    • The method must accept an integer year and asynchronously query for authors who have published one or more books in or after that year.
    • The implementation must adhere to all of the following EF Core best practices:
      • Use AsNoTracking() for this read-only query.
      • Filter the results on the database server (e.g., apply a Where clause before any materialization like ToListAsync).
      • Use a projection (Select) to return only the author's name and a collection of their recent book titles. The query should not return full Author or Book entities.

Expected result

The final submission should be a single block of C# code containing the complete implementations for all specified classes:

  1. The Author and Book entity classes with all required properties and navigation properties defined.
  2. The AuthorConfiguration class correctly implementing IEntityTypeConfiguration<Author> and using the Fluent API to set the primary key, required properties, max length, and the one-to-many relationship with Book entities, including the DeleteBehavior.Cascade rule.
  3. The BookConfiguration class correctly implementing IEntityTypeConfiguration<Book> and using the Fluent API to set the primary key, required properties, and the many-to-one relationship with the Author entity.
  4. The LibraryDbContext class inheriting from DbContext, defining DbSet properties for Authors and Books, and correctly applying the configurations within the overridden OnModelCreating method.
  5. A complete and correct implementation of the GetAuthorsWithRecentBooksAsync method. The implementation must be asynchronous and use a LINQ query against the DbContext that chains AsNoTracking(), a Where() clause for server-side filtering by year and author's book count, and a Select() clause to project the results into a new shape containing only author names and their corresponding recent book titles.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.