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:
Real-World Example Scenario
Letβs say you are building a simple blog application.
You need:
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.
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Post> Posts { get; set; }
}
Step 5: Configure Database Connection
Add connection string in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=BlogDb;Trusted_Connection=True;"
}
Register DbContext in Program.cs:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Step 6: Create Migration
Migration is used to create/update database schema.
dotnet ef migrations add InitialCreate
Step 7: Update Database
Apply migration to create database:
dotnet ef database update
π Now your database and tables are created automatically.
Step 8: Perform CRUD Operations
Example: Add a new user
var user = new User
{
Name = "Rahul",
Email = "[email protected]"
};
context.Users.Add(user);
context.SaveChanges();
Example: Fetch data
var users = context.Users.ToList();
Example: Include related data
var usersWithPosts = context.Users
.Include(u => u.Posts)
.ToList();
How Relationships Work in Code First
EF Core automatically detects relationships:
You can also configure relationships using Fluent API if needed.
Advantages of Code First Approach
Faster Development
No need to manually create tables.
Strongly Typed
Everything is written in C#.
Easy Maintenance
Changes can be handled via migrations.
Version Control Friendly
Database structure is tracked in code.
Common Mistakes to Avoid
Forgetting migrations
Always run migrations after model changes.
Incorrect connection string
Double-check database configuration.
Not using Include for relationships
Related data wonβt load automatically.
Large DbContext
Keep DbContext clean and modular.
Best Practices
Use Data Annotations or Fluent API
For better control over schema.
Separate Models and DTOs
Avoid exposing database models directly.
Use Repository Pattern (optional)
For better architecture in large apps.
Use Async Methods
await context.Users.ToListAsync();
Conclusion
The Code First approach in Entity Framework Core is one of the easiest and most efficient ways to manage databases in ASP.NET Core applications.
By defining your models in C#, using DbContext, and applying migrations, you can quickly build and maintain a database-driven application.
Start with simple projects like a blog or user management system, and gradually move to advanced features like Fluent API, relationships, and performance optimization.