Complete Guide to Entity Framework Core in ASP.NET Core
Welcome Developers! In this detailed walkthrough, we'll explore everything from the basics of Entity Framework Core (EF Core) to its practical use in enterprise-level ASP.NET Core development. Whether you're a beginner trying to understand data access or a developer looking to structure a maintainable database layer, this is for you.
πΉ What is Entity Framework Core?
EF Core is an open-source, cross-platform ORM (Object-Relational Mapper) from Microsoft. It acts as a bridge between your .NET objects and the underlying relational database, allowing you to query and manipulate data using strongly typed C# code instead of SQL.
Key Features:
- Supports LINQ queries, tracking changes, schema migrations
- Cross-platform support (.NET 6/7/8+ on Windows, macOS, Linux)
- Code-first and database-first approaches
- Integrates with DI and logging in ASP.NET Core
Comparison Table: EF Core vs Traditional ADO.NET
Feature | Entity Framework Core | ADO.NET |
---|---|---|
Abstraction | ORM - Works with models | Manual SQL operations |
Boilerplate Code | Minimal | Verbose and repetitive |
Data Tracking | Built-in | Manual |
LINQ Support | Yes | No |
Migration | Supported via CLI | Manual DB changes |
Visual Overview of EF Core Lifecycle

EF Core handles model creation, migrations, tracking, and querying seamlessly in the request lifecycle.
πΉ Installing EF Core Packages
You need to install a few NuGet packages depending on the database you plan to use (SQL Server, PostgreSQL, SQLite, etc.). For SQL Server:
// Install packages
> dotnet add package Microsoft.EntityFrameworkCore
> dotnet add package Microsoft.EntityFrameworkCore.SqlServer
> dotnet add package Microsoft.EntityFrameworkCore.Tools
πΉ Define Your Models
Each model represents a table in the database. Define your models using C# classes:
public class Product {
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public Category Category { get; set; } // Navigation Property
}
πΉ Configure Your DbContext
DbContext acts as a session between your app and the database:
public class AppDbContext : DbContext {
public DbSet Products { get; set; }
public DbSet Categories { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
// Fluent API (optional)
modelBuilder.Entity<Product>()
.HasOne(p => p.Category)
.WithMany()
.HasForeignKey("CategoryId");
}
}
πΉ Add DbContext to Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
πΉ Using Migrations
EF Core lets you keep your schema in sync with your models:
// Create the first migration
> dotnet ef migrations add InitialCreate
// Apply it to the database
> dotnet ef database update
πΉ CRUD Operations
EF Core tracks objects and performs operations like insert, update, delete:
// Create
var product = new Product { Name = "Keyboard", Price = 100 };
context.Products.Add(product);
context.SaveChanges();
// Read
var items = context.Products.ToList();
// Update
var prod = context.Products.First();
prod.Price = 120;
context.SaveChanges();
// Delete
context.Products.Remove(prod);
context.SaveChanges();
πΉ Async Queries
Async improves scalability:
var items = await context.Products.AsNoTracking().ToListAsync();
πΉ One-to-Many, Many-to-Many
public class Category {
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}
EF Core automatically builds the relationships.
πΉ Advanced Configurations
- Fluent API for precision control
- Shadow Properties
- Value Conversions (e.g., enum to string)
- Concurrency Tokens
πΉ Repository Pattern
Encapsulate database logic:
public interface IProductRepository {
Task<IEnumerable<Product>> GetAllAsync();
}
public class ProductRepository : IProductRepository {
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context) {
_context = context;
}
public async Task<IEnumerable<Product>> GetAllAsync() {
return await _context.Products.ToListAsync();
}
}
πΉ Best Practices
- Use
AsNoTracking()
for readonly queries - Use Unit of Work + Repository in large apps
- Write integration tests using in-memory DB
- Avoid large DbContext lifetimes
- Configure indexes and constraints via Fluent API
πΉ Real-world Scenario
In a shopping cart app, EF Core handles product catalog, orders, users, payments, and relationships between them using navigation properties and foreign keys.
π Summary
Entity Framework Core empowers developers to build scalable, maintainable, and robust database-driven applications using modern .NET technologies. Itβs an essential part of full-stack ASP.NET Core development and fits well in microservices, monoliths, and API-first designs.
π Mastering EF Core means you write less code, build faster, and stay future-ready!