ASP.NET Core Code First Approach Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      10 mins read      Difficulty-Level: beginner

ASP.NET Core Code First Approach: An In-Depth Guide for Beginners

Welcome to a comprehensive guide on the ASP.NET Core Code First Approach, designed to make understanding and implementing this method as easy and intuitive as possible. If you're new to ASP.NET Core and the Entity Framework Core, this step-by-step tutorial will equip you with the basics and help you build robust, data-driven applications.

Introduction to ASP.NET Core

ASP.NET Core is a high-performance, open-source, cross-platform framework for building modern web applications, microservices, and APIs using .NET. Introduced in 2016, ASP.NET Core has evolved significantly, offering a lightweight, modular architecture and support for both Windows and Linux operating systems.

Understanding the Entity Framework Core

The Entity Framework Core (EF Core) is the official Object-Relational Mapping (ORM) tool for .NET. It facilitates database interactions by enabling developers to work with databases using familiar .NET objects, rather than writing complex SQL queries. EF Core supports a variety of database systems, including SQL Server, SQLite, MySQL, and PostgreSQL.

What is the Code First Approach?

In the Code First approach, developers start by defining their model classes in code. EF Core then uses these classes to create the corresponding database schema automatically. If the model changes, the developer can update the database schema accordingly. This approach emphasizes coding first, promoting a more dynamic and flexible development process.

Step-by-Step Guide to Implementing Code First Approach

Step 1: Setting Up Your Development Environment

Before diving into the code first approach, ensure you have the necessary tools installed on your machine:

  • Visual Studio 2019 or Later: Microsoft's integrated development environment (IDE) with powerful tools for .NET development.
  • .NET SDK 5.0 or Later: The Software Development Kit required for building .NET applications.
  • NuGet Package Manager: Manages and installs third-party libraries, including EF Core packages.
Step 2: Creating a New ASP.NET Core MVC Project
  1. Open Visual Studio.
  2. Select "Create a new project".
  3. Choose "ASP.NET Core Web App (Model-View-Controller)" and click "Next".
  4. Enter your project name (e.g., "CodeFirstDemo") and choose a location to save it.
  5. Click "Create".
  6. In the new project dialog, choose the .NET version (.NET 5.0 or later) and click "Create".
Step 3: Adding EF Core Package

Ensure EF Core is included in your project by installing the necessary NuGet packages.

  1. Right-click on your project in the Solution Explorer and select "Manage NuGet Packages".
  2. Search for "Microsoft.EntityFrameworkCore.SqlServer" and install it.
  3. Also, install "Microsoft.EntityFrameworkCore.Tools" for command-line tools support.
Step 4: Defining Your Model Classes

Create POCO (Plain Old CLR Objects) classes that represent the entities in your application.

public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime EnrollmentDate { get; set; }
    
    public ICollection<Enrollment> Enrollments { get; set; }
}

public class Course
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    
    public ICollection<Enrollment> Enrollments { get; set; }
}

public class Enrollment
{
    public int StudentId { get; set; }
    public int CourseId { get; set; }
    public Grade? Grade { get; set; }

    public Student Student { get; set; }
    public Course Course { get; set; }
}

public enum Grade
{
    A, B, C, D, F
}
Step 5: Creating the DbContext

The DbContext class represents the session with the database. It allows querying and saving instances of your entities.

using Microsoft.EntityFrameworkCore;

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

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<Enrollment> Enrollments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Enrollment>()
            .HasKey(e => new { e.CourseId, e.StudentId });
    }
}
Step 6: Configuring the Database Connection

Open appsettings.json and add your database connection string.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CodeFirstDemoDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  ...
}

Configure the services in Startup.cs (for .NET 5.0 and later, this is typically Program.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddDbContext<SchoolContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Step 7: Creating the Database

Use EF Core migrations to create the database schema from your model.

  1. Open the Package Manager Console in Visual Studio (Tools -> NuGet Package Manager -> Package Manager Console).
  2. Run the following commands:
Add-Migration InitialCreate
Update-Database

Alternatively, you can use the .NET CLI:

dotnet ef migrations add InitialCreate
dotnet ef database update

These commands generate a migration script and apply it to the database, creating the necessary tables and relationships.

Step 8: Implementing CRUD Operations

Create controllers and views to handle CRUD (Create, Read, Update, Delete) operations for your entities.

  1. Right-click on the "Controllers" folder in Solution Explorer and select "Add -> Controller".
  2. Choose "MVC Controller with read/write actions, using Entity Framework" and click "Add".
  3. Select the model class (e.g., Student) and the data context class (SchoolContext).
  4. Click "Add" to scaffold the controller.

Repeat this process for other entities (Course, Enrollment).

Step 9: Running the Application
  1. Press F5 or click the "Start" button in Visual Studio to run the application.
  2. Navigate to the generated controllers to interact with your data (e.g., /Students, /Courses).

Additional Tips and Best Practices

  • Fluent API: Use the OnModelCreating method to configure entity relationships and database mapping using the Fluent API.
  • Data Annotations: Apply attributes to your model classes for additional configuration (e.g., [Required], [StringLength]).
  • Repository Pattern: Consider using the repository pattern to abstract data access and promote testability.
  • Version Control: Use version control systems like Git to manage changes to your database schema and models.
  • Seeding Data: Populate your database with initial data using migrations or seed methods.

Conclusion

The ASP.NET Core Code First Approach is a powerful way to build data-driven applications with minimal database schema setup. By starting with your model classes, EF Core handles the intricacies of database interactions, allowing you to focus on your application logic.

Through this step-by-step guide, you've learned how to set up an ASP.NET Core MVC project, define your model classes, configure the DbContext, and create the database schema using EF Core migrations. You've also seen how to implement CRUD operations and run your application.

As you continue to develop with ASP.NET Core and EF Core, explore additional features and best practices to enhance your applications' functionality and performance. Happy coding!


Feel free to ask any questions or seek further clarification on any part of the guide. Happy coding with ASP.NET Core and EF Core!