ASP.NET Core  

How to Use Entity Framework Core Code First Approach in ASP.NET Core

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.

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:

  • One-to-Many β†’ User β†’ Posts

  • Foreign Key β†’ UserId in Post

You can also configure relationships using Fluent API if needed.

Advantages of Code First Approach

  1. Faster Development

No need to manually create tables.

  1. Strongly Typed

Everything is written in C#.

  1. Easy Maintenance

Changes can be handled via migrations.

  1. Version Control Friendly

Database structure is tracked in code.

Common Mistakes to Avoid

  1. Forgetting migrations

Always run migrations after model changes.

  1. Incorrect connection string

Double-check database configuration.

  1. Not using Include for relationships

Related data won’t load automatically.

  1. Large DbContext

Keep DbContext clean and modular.

Best Practices

  1. Use Data Annotations or Fluent API

For better control over schema.

  1. Separate Models and DTOs

Avoid exposing database models directly.

  1. Use Repository Pattern (optional)

For better architecture in large apps.

  1. 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.