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.
// 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:
// 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:
// 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:
// 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:
Install Tools (One-time setup):
Ensure you have the global tool installed.bashdotnet tool install --global dotnet-efNote: If already installed, update it:
dotnet tool update --global dotnet-efAdd Required Package:
bashdotnet add package Microsoft.EntityFrameworkCore.DesignCreate a Migration:
This looks at yourAppDbContextand compares it to the last snapshot.bashdotnet ef migrations add InitialCreateOutput: A folder
Migrationsis created with C# files describing the table creation.Update the Database:
This translates the migration C# code into SQL and runs it against the database.bashdotnet ef database update
Imagination Time βοΈ
Think ofdotnet ef migrations addas packing your bags for a trip (preparing the changes), anddotnet ef database updateas 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) π±
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.
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.
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) ποΈ
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! β οΈ)
- Always use Async: Database I/O is slow. Using
ToListAsync(instead ofToList) prevents your server from freezing while waiting for data. - Filter Early: Do your
Where()logic before callingToList(). If you doToList().Where(...), you pull the entire database table into memory and filter it there. That is a disaster for performance. - 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
- Official Docs: Overview of Entity Framework Core
- Installation: Installing EF Core
- Migrations: Managing Database Schemas
- Performance: EF Core Performance Best Practices
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:
Define Entities:
- Create a
publicC# class namedAuthorwith the following properties:Id(int)Name(string)- A collection navigation property for related books, named
Books(e.g.,ICollection<Book>).
- Create a
publicC# class namedBookwith the following properties:Id(int)Title(string)PublishedYear(int)- The foreign key
AuthorId(int). - A reference navigation property to its
Author.
- Create a
Create Entity Configurations:
- Create a class
AuthorConfigurationthat implementsIEntityTypeConfiguration<Author>.- Configure
Idas the primary key. - Configure the
Nameproperty to be required and have a maximum length of 150 characters. - Configure the one-to-many relationship with
Book, specifying that deleting anAuthorshould also delete all their associatedBookentities (DeleteBehavior.Cascade).
- Configure
- Create a class
BookConfigurationthat implementsIEntityTypeConfiguration<Book>.- Configure
Idas the primary key. - Configure the
Titleproperty to be required. - Configure the many-to-one relationship back to
Authorusing theAuthorIdforeign key.
- Configure
- Create a class
Create the DbContext:
- Create a class
LibraryDbContextthat inherits fromDbContext. - Add
DbSet<Author>andDbSet<Book>properties namedAuthorsandBooksrespectively. - Override the
OnModelCreatingmethod to apply both theAuthorConfigurationandBookConfigurationyou created.
- Create a class
Implement the Data Service Method:
- Complete the
GetAuthorsWithRecentBooksAsyncmethod within the providedBookServiceclass. - The method must accept an integer
yearand asynchronously query for authors who have published one or more books in or after thatyear. - 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
Whereclause before any materialization likeToListAsync). - Use a projection (
Select) to return only the author's name and a collection of their recent book titles. The query should not return fullAuthororBookentities.
- Use
- Complete the
Expected result
The final submission should be a single block of C# code containing the complete implementations for all specified classes:
- The
AuthorandBookentity classes with all required properties and navigation properties defined. - The
AuthorConfigurationclass correctly implementingIEntityTypeConfiguration<Author>and using the Fluent API to set the primary key, required properties, max length, and the one-to-many relationship withBookentities, including theDeleteBehavior.Cascaderule. - The
BookConfigurationclass correctly implementingIEntityTypeConfiguration<Book>and using the Fluent API to set the primary key, required properties, and the many-to-one relationship with theAuthorentity. - The
LibraryDbContextclass inheriting fromDbContext, definingDbSetproperties forAuthorsandBooks, and correctly applying the configurations within the overriddenOnModelCreatingmethod. - A complete and correct implementation of the
GetAuthorsWithRecentBooksAsyncmethod. The implementation must be asynchronous and use a LINQ query against theDbContextthat chainsAsNoTracking(), aWhere()clause for server-side filtering by year and author's book count, and aSelect()clause to project the results into a new shape containing only author names and their corresponding recent book titles.