paint-brush
EF Core Migrations: A Step-by-Step Guide to Get Startedby@ssukhpinder
4,366 reads
4,366 reads

EF Core Migrations: A Step-by-Step Guide to Get Started

by Sukhpinder SinghMarch 9th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

EF Core is an object-relational mapping (ORM) framework that allows developers to interact with databases. One of the essential features of EF Core is its ability to handle database migrations. This article demonstrates EF Core migrations, why they're crucial, and how to use them with an example.
featured image - EF Core Migrations: A Step-by-Step Guide to Get Started
Sukhpinder Singh HackerNoon profile picture

Entity Framework Core (EF Core) is an object-relational mapping (ORM) framework that allows developers to interact with databases using .NET objects. One of the essential features of EF Core is its ability to handle database migrations.

Prerequisites

  • Basic C# programming language knowledge.
  • Basic OOPS concepts understanding


This article demonstrates EF Core migrations, why they're crucial, and how to use them with an example. So, to begin:


Introduction to C#


C# has been around for quite some period, and it continues to develop, obtaining more enhanced features.medium.com

Learning Objectives

  • How to use EF Core migration with example.


  • Why EF Core migrations are important

Getting Started

EF Core Migrations are a way of managing changes to your database schema over time. When you make changes to your database model (such as adding or removing tables or columns), you can create a migration that describes those changes.


Migrations are then used to update the database schema to match the new model.

Why Are EF Core Migrations Important?

EF Core Migrations are essential because they allow you to evolve your database schema over time while preserving data.


Without migrations, you would have to manually modify your database schema every time you make changes to your model, which can be time-consuming and error-prone.


Migrations also provide a way to version your database schema so that you can easily track changes and roll back to previous versions if needed.

How to Use EF Core Migrations?

To use EF Core Migrations, you'll need to follow a few steps:


  1. Create a new EF Core project. The first step is to create a new EF Core project in Visual Studio. You can do this by selecting "Create a new project", and then selecting "ASP.NET Core Web Application" and choosing the "Web Application (Model-View-Controller)" template.


  2. Create a database context. The next step is to create a database context class. This class manages interactions between your .NET objects and the database. To create a database context, create a new class in your project and inherit it from the DbContext class.


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


Create a Database Model

After creating a database context, you'll need to create a database model. This model represents the structure of your database and is used by EF Core to generate database tables and columns.


To create a database model, create a new class in your project, and define its properties as database fields.


public class MyModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}


Enable EF Core Migrations

Next, you need to enable EF Core Migrations in your project. To do this, open the Package Manager Console, and enter the following command:


PM> Install-Package Microsoft.EntityFrameworkCore.Tools


This package contains the tools needed to create and manage EF Core Migrations.


Create a Migration

With EF Core Migrations enabled, you can create your first migration. To create a migration, open the Package Manager Console, and enter the following command:


PM> Add-Migration InitialCreate


This will create a new migration called "InitialCreate" that describes the changes you've made to your database model. You can view the contents of the migration in the "Migrations" folder of your project.


Update the Database

After creating a migration, you can update the database schema to match the new model. To do this, open the Package Manager Console, and enter the following command:


PM> Update-Database


This will apply the migration to the database and update its schema.

Example

Let's look at an example of using EF Core Migrations. Suppose we want to create a simple "Students" table with two columns: "Id" and "Name". We'll start by creating a new ASP.NET Core Web Application project in Visual Studio.


  1. Create a new EF Core project. Create a new ASP.NET Core Web Application project in Visual Studio. Select the "Web Application (Model-View-Controller)" template, and choose "Individual User Accounts" for Authentication. Name the project "EFCoreMigrationsExample".


  2. Create a database context. Create a new class called "MyDbContext" in the project's "Models" folder, and inherit it from the DbContext class.


using Microsoft.EntityFrameworkCore;
namespace EFCoreMigrationsExample.Models
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }
        public DbSet<Student> Students { get; set; }
    }
}


The "Students" property is a DbSet representing our database's "Students" table.


Create a Database Model

Create a new "Student" class in the project's "Models" folder, and define its properties.

namespace EFCoreMigrationsExample.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}


Enable EF Core Migrations

Open the Package Manager Console and enter the following command to install the EF Core tools package:

PM> Install-Package Microsoft.EntityFrameworkCore.Tools


Create a Migration

Open the Package Manager Console, and enter the following command to create a migration:

PM> Add-Migration InitialCreate


This will create a new migration called "InitialCreate" that describes the changes we've made to our database model.


The migration file should look like this:

using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCoreMigrationsExample.Migrations
{
    public partial class InitialCreate : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Students",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Students", x => x.Id);
                });
        }
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Students");
        }
    }
}


The migration creates a new table called "Students" with columns for "Id" and "Name".

Update the database Open the Package Manager Console, and enter the following command to update the database schema:


PM> Update-Database


This will apply the migration to the database and update its schema.


Now we can add, update, and delete students in our database using EF Core. For example, we can add a new student to the database like this:

using EFCoreMigrationsExample.Models;

namespace EFCoreMigrationsExample.Controllers
{
    public class HomeController : Controller
    {
        private readonly MyDbContext _context;
        public HomeController(MyDbContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            var student = new Student
            {
                Name = "John"
            };
            _context.Students.Add(student);
            _context.SaveChanges();
            return View();
        }
    }
}


This code creates a new instance of the Student class and sets its Name property to "John". It then adds the student to the Students DbSet and saves changes to the database.

Conclusion

EF Core Migrations provide a convenient way to manage database schema changes in your application.


This article shows how to create a simple database schema using EF Core migrations, including creating a DbContext, defining a model, making a migration, and updating the database schema.


This is just the beginning of what EF Core can do. You can use EF Core to query and manipulate data, create complex relationships between tables, and more. With its ease of use and wide range of features, EF Core is an excellent choice for building data-driven applications in .NET.


This article has helped get you started with EF Core migrations. If you have any questions or comments, please leave them below. Happy coding!

Follow Me On

C# Publication, LinkedIn, Instagram, Twitter, Dev.to


Also published here