Entity Framework

Entity Framework (EF) is Microsoft’s flagship Object‑Relational Mapping (ORM) framework for .NET. It enables developers to work with a database using .NET objects, eliminating most of the data-access code they would usually need to write.

On this page Overview Getting Started Model Creation Queries Migrations Performance Tips API Reference

Overview

EF provides the following features:

Getting Started

Install the EF Core package via NuGet:

dotnet add package Microsoft.EntityFrameworkCore

For SQL Server support:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Model Creation

Define your entity classes and a DbContext subclass:

using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}

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

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

Queries

Typical LINQ query examples:

// Retrieve blogs with at least one post
var blogs = await context.Blogs
    .Where(b => b.Posts.Any())
    .ToListAsync();

// Load a blog with its posts (eager loading)
var blog = await context.Blogs
    .Include(b => b.Posts)
    .FirstOrDefaultAsync(b => b.BlogId == 1);

Migrations

Manage schema changes using the migrations CLI:

// Add a new migration
dotnet ef migrations add AddPostPublishedDate

// Apply pending migrations
dotnet ef database update

Performance Tips

API Reference

Explore the full API documentation: