Using Migrations in EF Core

If you are an Entity Framework veteran who has worked extensively with EF 6.x and prior versions, then Migrations should come as no surprise to you!

The good news is that as you transition from EF 6.x to EF Core, Migrations are not much different to what you are used to using with EF 6.x. So it begs the question, how do I use Migrations in EF Core. Well, this is exactly what this article is about.

PM>add-migration init
To undo this action, use Remove-Migration.
PM>

This action would create a migration script as seen in the image below. Pay close attention to the Migrations folder in that the add-migration command created a migration file xxx_init.cs. It also created a ModelSnapshot. This file is used by Entity Framework to keep state of the current model which is then used to apply changes from your model to the database when migrations are run the next time.

In EF 6.x, when you run the add-migration command, the ModelSnapshot file is created in the database which makes it harder to version control this file in Source Control. So the EF team decided to lump this file with the migration file in the Migrations folder instead to facilitate version control.

1Migrations

 

public partial class init : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Departments",
                columns: table => new
                {
                    depID = table.Column(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    depName = table.Column(nullable: true),
                    location = table.Column(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Departments", x => x.depID);
                });

            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    empID = table.Column(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    age = table.Column(nullable: false),
                    depID = table.Column(nullable: false),
                    empName = table.Column(nullable: true),
                    EmployeesempID = table.Column(nullable: true),
                    MiddleName = table.Column(nullable: true),
                    title = table.Column(nullable: true)
                },

As part of the migration file, it creates a bunch of code including the Down method below which is used in the event the migration needs to be restored to its previous state:

protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");

            migrationBuilder.DropTable(
                name: "Departments");
        }

The next step is for the migrations update the database, but before that, let’s take a quick look at some of the EF Core commands:

EFCommands

You can also script the migration by simply using Script-Migration command which is also listed in the image above.

PM> script-migration

This will create T-SQL that matches the shape of your entity. You can then use this script to execute directly against SQL Server. This also gives the developer or the DBA some flexibility to tweak the script if necessary. If you rather not use the script-migration command, you are welcome to use the good’ol update-database command instead.

IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
    );
END;

GO

CREATE TABLE [Departments] (
    [depID] int NOT NULL IDENTITY,
    [depName] nvarchar(max),
    [location] nvarchar(max),
    CONSTRAINT [PK_Departments] PRIMARY KEY ([depID])
);

GO

CREATE TABLE [Employees] (
    [empID] int NOT NULL IDENTITY,
    [age] int NOT NULL,
    [depID] int NOT NULL,
    [empName] nvarchar(max),
    [EmployeesempID] int,
    [MiddleName] nvarchar(max),
    [title] nvarchar(max),
    CONSTRAINT [PK_Employees] PRIMARY KEY ([empID]),
    CONSTRAINT [FK_Employees_Departments_depID] FOREIGN KEY ([depID]) REFERENCES [Departments] ([depID]) ON DELETE CASCADE,
    CONSTRAINT [FK_Employees_Employees_EmployeesempID] FOREIGN KEY ([EmployeesempID]) REFERENCES [Employees] ([empID]) ON DELETE NO ACTION
);

GO

That’s all there is to it. Hope you liked it!

Obi

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in ORM. Bookmark the permalink.