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:
- Productivity: Reduces boilerplate code for data access.
- Maintainability: Easier to manage and understand data access logic.
- Cross-Platform: Works on Windows, macOS, and Linux.
- Extensibility: Allows customization and integration with other libraries.
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:
- Improved performance and memory usage.
- Advanced querying capabilities, including JSON support.
- Keyless entities and owned types for more flexible model design.
- Enhanced support for Cosmos DB and other NoSQL databases.
- TPH (Table-Per-Hierarchy) and TPT (Table-Per-Type) inheritance mapping.
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:
- Install the EF Core NuGet packages:
(Replacedotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer
SqlServer
with your target database provider, e.g.,Npgsql.EntityFrameworkCore.PostgreSQL
,MySql.EntityFrameworkCore
, etc.) - Define your model classes: Create plain old C# objects (POCOs) that represent your database entities.
- Define your
DbContext
: This class represents a session with the database and is used to query and save data. - 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:
- Entities: POCO classes that represent tables in your database.
DbContext
: The gateway to your database. It allows you to query entities and save changes.DbSet<TEntity>
: Represents a collection of entities of a given type. It's typically exposed as a property on yourDbContext
.
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:
- Create new tables based on your entity definitions.
- Alter table schemas when your entity classes change (e.g., adding properties).
- Update data during schema changes.
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.
- Asynchronous operations: Use
ToListAsync()
,SaveChangesAsync()
etc., to avoid blocking threads. - Eager loading: Use
Include()
to load related data in a single query, avoiding N+1 query problems. - Projection: Select only the data you need using LINQ's
Select()
. - Compiled queries: For frequently executed queries, consider compiling them for better performance.
- Batching: EF Core automatically batches updates for efficiency.
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.