Entity Framework for .NET Core
Entity Framework (EF) is Microsoft’s modern object‑relational mapper (ORM) that enables .NET developers to work with a database using .NET objects, eliminating most of the data‑access code they usually need to write.
Key Features
- Fully async LINQ queries
- Cross‑platform support (Windows, Linux, macOS)
- Migrations for evolving database schemas
- Model‑first, code‑first, and database‑first workflows
- Built‑in caching and change tracking
Getting Started
Install the EF Core packages via dotnet
CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # for SQL Server
dotnet add package Microsoft.EntityFrameworkCore.Tools # for migrations
Create a DbContext
and your entity classes:
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=.;Database=Blogging;Trusted_Connection=True;");
}
public class Blog
{
public int BlogId { get; set; }
public string? Url { get; set; }
public List<Post> Posts { get; set; } = 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; } = null!;
}
Run a migration to create the database schema:
dotnet ef migrations add InitialCreate
dotnet ef database update