Entity Framework
Overview
Entity Framework (EF) is Microsoft’s recommended data access technology for new .NET applications. It provides an object–relational mapper (ORM) that enables .NET developers to work with a database using .NET objects, eliminating the need for most of the data-access code that developers usually need to write.
Getting Started
Install the EF Core package and create a DbContext.
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=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
Modeling Data
Define entity classes that map to database tables.
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; }
}
Use data annotations or the Fluent API for configuration.
Queries
EF supports LINQ queries that are translated to SQL.
using var db = new BloggingContext();
var blogs = db.Blogs
.Where(b => b.Url.Contains("dotnet"))
.OrderBy(b => b.BlogId)
.ToList();
Include related data with Include:
var blogsWithPosts = db.Blogs
.Include(b => b.Posts)
.ToList();
Saving Data
Changes are tracked automatically. Call SaveChanges to persist.
using var db = new BloggingContext();
var blog = new Blog { Url = "https://devblogs.microsoft.com/dotnet" };
db.Blogs.Add(blog);
db.SaveChanges();
Update and delete operations follow the same pattern.
Performance Tips
- Use
AsNoTrackingfor read‑only queries. - Batch multiple commands with
SaveChangesinstead of one per entity. - Limit results with
TakeandSkipfor paging. - Prefer compiled queries for high‑traffic scenarios.
API Reference
Key classes and interfaces:
DbContextDbSet<TEntity>ModelBuilder(Fluent API)EntityEntryRelationalDatabaseFacadeExtensions
Visit the full API documentation for detailed members.