Entity Framework

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.

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

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=...");