SQL Database Migration in .NET with Entity Framework Core

fredchuks

Fred Chuks

Posted on June 30, 2024

SQL Database Migration in .NET with Entity Framework Core

Introduction

Recently, I had an issue with migration in .NET using entity framework core. I kept getting error reports on the NuGet package manager console. This article would provide a detailed explanation of how I resolved this problem. I am Fredrick Chukwuma, a .NET Developer that is result and process-oriented.

What Is Entity Framework?

Entity Framework is a modern object-relation mapper that lets you build a clean, portable, and high-level data access layer with .NET (C#) across a variety of databases. It makes programming easier and faster.

Prerequisites

To follow along, ensure you have the following:

  • Visual studio

  • Familiarity with .NET and the Entity framework

  • Installed .NET locally

  • A SQL Server or Azure SQL database

Step 1: Create a new ASP.NETCore Web API Project

Open visual studio, click on new project, select ASP.NETCore Web API and configure the project
https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80t5udbua0yr3jsbt26l.png

Step 2: Create a Model

Create a new folder named "Models" in the root directory. Then create a new c# class named "Student.cs" and add properties as done below:

 public class Student
    {
        public Guid Id { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? Department { get; set; }

    }
Enter fullscreen mode Exit fullscreen mode

Note: The question mark at the end of each property data type is to make it nullable.

Step 3: Include connection string in appsettings.json file

Open the appsettings.json file then add the line below. Replace the server name with the name of your server

"ConnectionStrings": { "DefaultConnection": "Server=Your-ServerName\\SQLEXPRESS;Database=StudentApp;Trusted_Connection=True;TrustServerCertificate=True" }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create and Register your App DbContext

Create a folder named Data in your root directory then create an AppDbContext Class in the Data folder and inherit from the DbContext class (The DbContext class is an in-built class in .NET). Also, create a field in this class as shown below

public class ApplicationDbContext : DbContext
    {

            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
            {

            }

            public DbSet<Student> Students { get; set; }

    }
Enter fullscreen mode Exit fullscreen mode

Register a service in the program class as shown below:

builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Enter fullscreen mode Exit fullscreen mode

Step 5: Install Entity Framework Core Packages

On the menu bar, click on tools, select NuGet package manager , then select Manage NuGet Packages For solution . Click browse and install the following packages:

  • Microsoft.EntityFramewrokCore

  • Microsoft.EntityFramewrokCore.SqlServer

  • Microsoft.EntityFramewrokCore.Tools

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wr949tsxik9qgngxdef0.png
Note: Ensure you install the version of each package that relates to the .NET Framework installed on your system.

Step 6: Add Migration

On the menu bar, click on tools, select NuGet package manager, then select Package Manager console.
On the console type "add-migration" space "AddStudentTable" (this is the name of the migration, you can use any name of your choice) then press enter.
https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6drp7cuktsi2pj3ervdl.png

When, the build is done, on the Package Manager console, type "update-database" then press enter.
https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlavij3a84bc1scqme4e.png
Once you see this, you're done! Congrats! You understand migrations in .NET using Entity Framework core!

Conclusion

As easy as these steps seem, I didn't find it funny a while ago. I encountered a serious issue because I couldn't get the accurate name of my local server and hence my "connection string" was faulty. I also had little idea of the AppDbContext class I was suppose to create to enable a smooth migration. I kept seeing error messages on my Package Manager console, but I figured it out in the end.
I'm loving the whole programming experience as I've seen myself transform from a "hello world" novice to where I am now.
I am also very excited to be a part of the HNG Internship 11. I've heard so much about how this internship program pushes individuals to explore their untapped potentials. I opted in for this internship when I came across the opportunity because I want to ace my programming skills, become a better developer, meet other developers and great minds. I'm really anticipating what it holds.
I will also advice individuals that wish to take their tech journey to the next level to apply for free via https://hng.tech/internship
There's also a premium package that gives you more opportunities. You can apply here https://hng.tech/premium
HNG also offers the best tech talents for individuals looking to hire for their firm https://hng.tech/hire

πŸ’– πŸ’ͺ πŸ™… 🚩
fredchuks
Fred Chuks

Posted on June 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related