Introduction
In modern web development, managing databases efficiently is a crucial part of building scalable applications. In ASP.NET Core, Entity Framework Core (EF Core) provides a powerful way to work with databases using C# instead of writing complex SQL queries.
One of the most popular approaches in EF Core is the Code First approach. It allows developers to define the database structure using C# classes and automatically generate the database from that code.
In this article, we will understand how to use Entity Framework Core Code First in ASP.NET Core step-by-step, using simple language and real-world examples.
What is Entity Framework Core?
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that helps developers interact with databases using C# objects.
👉 Instead of writing SQL queries, you work with:
Classes
Objects
LINQ queries
This makes development faster, cleaner, and easier to maintain.
What is the Code First Approach?
Code First means:
👉 You write your model classes first, and EF Core creates the database based on those classes.
Flow:
C# Classes → EF Core → Database Tables
This approach is widely used because:
Easy to manage using code
Version control friendly
Ideal for new projects
Real-World Example Scenario
Let’s say you are building a simple blog application.
You need:
Users
Posts
Instead of creating tables manually, you define classes, and EF Core creates the database.
Step 1: Create ASP.NET Core Project
You can create a project using Visual Studio or CLI:
dotnet new webapi -n BlogApp
Step 2: Install Required Packages
Install EF Core packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Step 3: Create Model Classes
Create a folder named Models and add classes.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Explanation
Each class becomes a table
Properties become columns
Relationships are handled automatically
Step 4: Create DbContext Class
DbContext is the bridge between your application and database.

Join the conversation! Your thoughts help the community grow.