Entity Framework Core Concepts

This document provides a comprehensive overview of the fundamental concepts underpinning Entity Framework Core (EF Core), Microsoft's modern object-relational mapper (ORM) for .NET.

Introduction

Entity Framework Core is a lightweight and extensible version of the popular Entity Framework data access technology. It allows developers to work with databases using .NET objects, abstracting away much of the complexity of SQL and database interactions.

Key benefits of using EF Core include:

What's New in EF Core

EF Core has evolved significantly since its initial release. Each new version introduces performance improvements, new features, and support for the latest database technologies. Notable advancements include:

For detailed release notes, refer to the official EF Core documentation.

Getting Started with EF Core

Getting started with EF Core involves a few simple steps:

  1. Install the EF Core NuGet packages:
    dotnet add package Microsoft.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    (Replace SqlServer with your target database provider, e.g., Npgsql.EntityFrameworkCore.PostgreSQL, MySql.EntityFrameworkCore, etc.)
  2. Define your model classes: Create plain old C# objects (POCOs) that represent your database entities.
  3. Define your DbContext: This class represents a session with the database and is used to query and save data.
  4. Configure your database connection: Specify the connection string in your application's configuration.

Core Concepts

Understanding the following core concepts is crucial for effective use of EF Core:

Models

A model in EF Core represents the structure of your data. It consists of:

Example Entity:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

Queries

EF Core allows you to query your database using LINQ (Language Integrated Query). The DbContext provides access to your DbSet<TEntity> properties, which can then be queried.

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
                       .Where(b => b.Url.Contains("microsoft"))
                       .OrderBy(b => b.Url)
                       .ToList();

    foreach (var blog in blogs)
    {
        Console.WriteLine(blog.Url);
    }
}

EF Core translates your LINQ queries into SQL statements executed against the database.

Change Tracking

When EF Core retrieves entities from the database, it starts tracking them. This means it keeps a record of the original state of each property. When you modify an entity, EF Core detects these changes and knows which updates need to be sent to the database.

The DbContext manages the state of tracked entities (Added, Modified, Deleted, Unchanged).

Saving Changes

To persist changes made to entities back to the database, you call the SaveChanges() method on your DbContext instance.

using (var context = new BloggingContext())
{
    var newBlog = new Blog { Url = "http://example.com" };
    context.Blogs.Add(newBlog);
    await context.SaveChangesAsync(); // Saves the new blog to the database
}

SaveChanges() generates and executes the necessary SQL INSERT, UPDATE, or DELETE statements based on the tracked changes.

Migrations

Migrations are EF Core's way of incrementally evolving your database schema to match your data model. They allow you to:

You can manage migrations using the .NET CLI or Package Manager Console:

// Add a new migration
dotnet ef migrations add InitialCreate

// Apply migrations to the database
dotnet ef database update

Relationships

EF Core supports mapping relationships between entities, such as one-to-one, one-to-many, and many-to-many.

Example One-to-Many:

public class Blog
{
    // ...
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; } // Foreign key
    public Blog Blog { get; set; }
}

EF Core automatically infers these relationships and sets up foreign keys and navigation properties.

Performance

While EF Core simplifies data access, performance considerations are important for large-scale applications.

Note: Always profile your application to identify performance bottlenecks. EF Core provides tools and techniques to optimize data access.
Tip: Explore the official EF Core documentation for advanced topics like Value Objects, Query Types, raw SQL queries, and database provider-specific features.

This document provides a foundational understanding of Entity Framework Core. For more in-depth information and advanced scenarios, please consult the comprehensive Microsoft Learn documentation for EF Core.