Entity Framework Core In-Depth
On This Page
Introduction to Entity Framework Core
Entity Framework Core (EF Core) is a modern, open-source, cross-platform version of the familiar Entity Framework data access technology. It's a lightweight, extensible, and high-performance Object-Relational Mapper (ORM) for .NET that enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers traditionally need to write.
EF Core maps your .NET objects to your database schema. This abstraction allows you to interact with your data using strongly-typed objects and LINQ queries, making your code more readable, maintainable, and less prone to errors. It supports a wide range of database providers, including SQL Server, PostgreSQL, MySQL, SQLite, Oracle, and more.
Core Concepts
Understanding the fundamental building blocks of EF Core is crucial for effective use. These include:
- DbContext: The primary class used to interact with the database. It represents a session with the database and can be used to query and save data.
- DbSet<TEntity>: Represents a collection of entities of a particular type within a
DbContext
. It's used to perform CRUD (Create, Read, Update, Delete) operations. - Entities: Plain old CLR objects (POCOs) that represent the tables in your database.
- Database Provider: A NuGet package that translates EF Core operations into commands for a specific database.
- Model: The in-memory representation of your database schema, including entities, relationships, and constraints.
Getting Started with EF Core
This section guides you through the initial steps of setting up EF Core in your .NET application. You'll learn how to:
- Install the necessary EF Core NuGet packages.
- Configure your
DbContext
. - Scaffold a
DbContext
and entity types from an existing database (Database-First approach). - Define your model from scratch and create the database (Code-First approach).
Modeling Your Data
EF Core provides flexible ways to define your data model:
1. Conventions
EF Core uses a set of default conventions to infer your model. For example, a public property of a type is mapped to a column, and a DbSet<TEntity>
property on your DbContext
is mapped to a table.
2. Data Annotations
You can use data annotations in your entity classes to configure aspects of your model, such as primary keys, foreign keys, and column properties.
public class Blog
{
public int Id { get; set; } // Conventionally the primary key
[Required] // Data annotation for NOT NULL
[MaxLength(200)] // Data annotation for string length
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
3. Fluent API
For more complex configurations or when data annotations are not sufficient, you can use the Fluent API by overriding the OnModelCreating
method in your DbContext
.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasIndex(b => b.Url)
.IsUnique();
}
Querying Data with LINQ
EF Core leverages Language Integrated Query (LINQ) to allow you to query your data in a strongly-typed and expressive way. You can filter, sort, group, and project your data directly in C# code.
// Get all blogs from a specific URL
var blogs = context.Blogs
.Where(b => b.Url.Contains("example.com"))
.OrderBy(b => b.Url)
.ToList();
// Include related data (e.g., posts for each blog)
var blogsWithPosts = context.Blogs
.Include(b => b.Posts)
.ToList();
Saving Data (Create, Update, Delete)
EF Core simplifies the process of persisting changes to your database.
Adding New Entities
var newBlog = new Blog { Url = "http://newblog.com" };
context.Blogs.Add(newBlog);
await context.SaveChangesAsync();
Updating Existing Entities
EF Core tracks changes automatically for entities retrieved through the context. For detached entities, you can use Update
or mark entities as modified.
var existingBlog = await context.Blogs.FindAsync(1);
if (existingBlog != null)
{
existingBlog.Url = "http://updatedblog.com";
await context.SaveChangesAsync();
}
Deleting Entities
var blogToDelete = await context.Blogs.FindAsync(2);
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
await context.SaveChangesAsync();
}
Database Migrations
EF Core Migrations provide a way to incrementally update your database schema to match your evolving data model without losing existing data.
- Add-Migration: Creates a new migration based on changes in your model.
- Update-Database: Applies pending migrations to the database.
- Script-Migration: Generates SQL scripts for migrations.
Advanced Topics
EF Core offers a rich set of features for more complex scenarios:
- Transaction Management: Handling database transactions for atomic operations.
- Concurrency Control: Managing concurrent data modifications to prevent conflicts.
- Raw SQL Queries: Executing raw SQL commands when LINQ is not sufficient or for performance optimization.
- Stored Procedures: Calling stored procedures from EF Core.
- Change Tracking: Understanding how EF Core detects and tracks changes to entities.
- Lazy Loading, Eager Loading, and Explicit Loading: Strategies for loading related data.
- Dependency Injection Integration: Using EF Core with .NET's built-in DI container.
This in-depth documentation aims to provide a comprehensive understanding of EF Core, empowering you to build robust and efficient data-driven applications.