Entity Framework Core
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It allows developers to work with a database using .NET objects, eliminating the need for most of the data-access code they typically need to write.
Introduction to Entity Framework Core
EF Core is an evolution of the popular Entity Framework. It's lightweight, extensible, and has excellent performance. It enables you to:
- Query your data as strongly-typed objects.
- Persist your object model to a relational database.
- Manage database schema changes using migrations.
Getting Started with EF Core
To get started with EF Core, you'll typically need to:
- Install the necessary NuGet packages. For example, for SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools - Define your domain entities (POCO classes).
- Create a
DbContextclass that represents a session with the database and can be used to query and save data. - Configure your model, either by convention or by using the Fluent API or Data Annotations.
- Set up your database connection string.
Example Entity:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual 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; }
public virtual Blog Blog { get; set; }
}
Example DbContext:
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Fluent API configuration can go here
modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired().HasMaxLength(200);
}
}
Core Concepts
DbContext: Represents a session with the database and is the primary way to interact with your data.DbSet<TEntity>: A collection of elements of a given entity type. It's usually accessed via a property on yourDbContext.- Entities: Plain Old CLR Objects (POCOs) that represent the tables in your database.
- Model Configuration: How EF Core understands your entities and how they map to the database. This can be done via conventions, Data Annotations, or the Fluent API.
Database Migrations
EF Core Migrations is a powerful feature that allows you to incrementally update your database schema to keep it in sync with your domain model. You can:
- Add a migration: Captures the changes in your model and generates C# code to apply those changes to the database.
dotnet ef migrations add InitialCreate - Apply migrations: Updates your database schema.
dotnet ef database update - Revert migrations: Roll back changes.
dotnet ef commands.
Querying Data
You can query data using LINQ. EF Core translates your LINQ queries into SQL.
using var context = new BloggingContext();
// Get all blogs
var blogs = context.Blogs.ToList();
// Find a specific blog by ID
var specificBlog = context.Blogs.Find(1);
// Query with filtering and ordering
var popularPosts = context.Posts
.Where(p => p.Content.Length > 100)
.OrderByDescending(p => p.PostId)
.ToList();
// Include related data
var blogsWithPosts = context.Blogs.Include(b => b.Posts).ToList();
Saving Data
You can add, modify, and delete entities. Changes are tracked by the DbContext and then committed to the database.
using var context = new BloggingContext();
// Add a new blog
var newBlog = new Blog { Url = "http://example.com" };
context.Blogs.Add(newBlog);
context.SaveChanges(); // Persists the changes
// Update a blog
var blogToUpdate = context.Blogs.Find(1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "http://updated-example.com";
context.SaveChanges();
}
// Remove a post
var postToRemove = context.Posts.Find(5);
if (postToRemove != null)
{
context.Posts.Remove(postToRemove);
context.SaveChanges();
}
Advanced Topics
- Raw SQL Queries
- Concurrency Control
- Performance Tuning
- Entity States
- Change Tracking
- Relationships (One-to-Many, Many-to-Many)