Introduction
Entity Framework Core (EF Core) is a modern, open‑source, object‑relational mapper (ORM) for .NET. It enables developers to work with a database using .NET objects, eliminating the need for most data‑access code that developers usually need to write.
Setup & Installation
Install the EF Core packages via dotnet CLI or NuGet:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer // or any provider
dotnet add package Microsoft.EntityFrameworkCore.Tools
Configure your DbContext in Program.cs:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
Data Modeling
Define entity classes and a DbContext:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
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; }
public Blog Blog { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
}
Working with Migrations
Create and apply migrations using the CLI:
dotnet ef migrations add InitialCreate
dotnet ef database update
Inspect the generated migration files to understand the schema changes.
Querying Data
EF Core supports LINQ queries. Example:
using var context = new AppDbContext();
var blogs = await context.Blogs
.Include(b => b.Posts)
.Where(b => b.Url.Contains("dotnet"))
.OrderBy(b => b.BlogId)
.ToListAsync();
Use AsNoTracking for read‑only queries to improve performance.
Performance Tips
- Prefer
AsNoTrackingwhen updates aren’t required. - Batch updates/inserts with
SaveChangesAsyncin a single context. - Use compiled queries for frequently executed statements.
- Avoid eager loading large navigation graphs; use explicit loading when needed.
Further Resources
| Topic | Link |
|---|---|
| Official Docs | EF Core Documentation |
| GitHub Repo | dotnet/efcore |
| Migration Guide | Migrations Overview |
| Performance Guide | Performance Best Practices |