Overview
Entity Framework (EF) is Microsoft’s flagship object‑relational mapper (ORM) for .NET. It enables developers to work with a database using .NET objects, eliminating most of the data-access code they’d typically need to write.
- Code‑first and database‑first approaches
- LINQ support for expressive queries
- Change tracking and automatic migrations
- Cross‑platform with .NET Core and .NET Framework
Getting Started
Install EF via NuGet and create a DbContext
class.
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
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 options)
=> options.UseSqlServer(@"Server=.;Database=Blogging;Trusted_Connection=True;");
}
LINQ Queries
EF translates LINQ to SQL under the hood. Use eager, lazy, or explicit loading.
using (var db = new BloggingContext())
{
var recentPosts = db.Posts
.Where(p => p.PublishedDate > DateTime.Now.AddDays(-30))
.OrderByDescending(p => p.PublishedDate)
.Take(10)
.ToList();
}
Migrations
Manage schema changes with EF Migrations.
dotnet ef migrations add InitialCreate
dotnet ef database update
Rollback:
dotnet ef migrations remove
dotnet ef database update LastGoodMigration
Performance Tips
- Use
NoTracking
for read‑only queries. - Batch inserts/updates with
SaveChanges
after bulk operations. - Avoid N+1 queries – use
Include
for related data. - Cache compiled queries when possible.
FAQ
Is EF suitable for large databases?
Yes, with proper tuning—use explicit loading, limit result sets, and consider compiled queries.
Can I use EF with PostgreSQL?
Install Microsoft.EntityFrameworkCore.Npgsql
and configure the provider.
options.UseNpgsql("Host=...;Database=...;Username=...;Password=...");