Entity Framework Core Deep Dive in ASP.NET Core

Now that we can build APIs, it's time to hook them up to a database using Entity Framework Core (EF Core), the official ORM (Object-Relational Mapper) for .NET.

In this post, we'll dive into how to use EF Core with ASP.NET Core to persist, query, and manage data cleanly.


🧱 Step 1: Install EF Core Packages

If you're using SQL Server:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

If you're using another DB (e.g., PostgreSQL), use the relevant provider.


🗃️ Step 2: Create Your DbContext

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}

    public DbSet<Product> Products { get; set; }
}

Add your model if you haven't already:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

⚙️ Step 3: Configure in Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

In appsettings.json:

"ConnectionStrings": {
  "DefaultConnection": "Server=localhost;Database=MyDb;Trusted_Connection=True;"
}

🛠️ Step 4: Add Migrations & Update DB

dotnet ef migrations add InitialCreate
dotnet ef database update

EF will scaffold the database based on your models and context.


📦 CRUD with EF Core

In your controller or service, inject AppDbContext:

private readonly AppDbContext _context;

public ProductsController(AppDbContext context)
{
    _context = context;
}

[HttpGet]
public async Task<IActionResult> GetAll() =>
    Ok(await _context.Products.ToListAsync());

[HttpPost]
public async Task<IActionResult> Create(Product product)
{
    _context.Products.Add(product);
    await _context.SaveChangesAsync();
    return CreatedAtAction(nameof(GetAll), new { id = product.Id }, product);
}

🔗 Relationships Example

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CategoryId { get; set; }

    public Category Category { get; set; }
}

EF handles foreign keys and joins for you. Just use .Include() when querying:

_context.Products.Include(p => p.Category).ToList();

🧪 Bonus: Seeding Data

Inside your DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().HasData(
        new Product { Id = 1, Name = "Sample", Price = 9.99M }
    );
}

✅ Up Next

We’ve got data flowing! Now let’s secure it.

Next: Authentication & Authorization with JWT — protecting your APIs the modern way.

➡️ Authentication & Authorization with JWT →

0
Subscribe to my newsletter

Read articles from Esanju Babatunde directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Esanju Babatunde
Esanju Babatunde