Tech Jobs Logo

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 Lifecycle Diagram

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!

Why Choose Us?

Browse Jobs & Companies