Add migration

Add a migration for the new property

whenever me we make changes to the entities, we need to create a migration and apply it to the database so that they both are In Sync

create a migration

Let us create a migration for this new field as shown below

dotnet ef migrations add CityAdded

After this command has executed, we see that a new file has been created inside the migrations folder and the code in it looks like this

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace EFGetStarted.Migrations
{
    /// <inheritdoc />
    public partial class CityAdded : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "City",
                table: "Students",
                type: "nvarchar(max)",
                nullable: false,
                defaultValue: "");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "City",
                table: "Students");
        }
    }
}

This is the code required to add the new column 2 hours students table in SQL Server database. Entity framework analyzed what has changed and then created suitable code for it all by itself!

Apply migration

the database is still not modified so let us apply the migration with the command below

dotnet ef database update

Now run the application again

What happens?

This time there won't be any exception, but we have neither any data in the city column nor we have included it while displaying!

As an exercise, you can write the code to modify a student entity and updated it's City column to have some data and display the same!

Any modifications to the entities require that we add a migration and apply it to the database similarly!

For production scenario, we can apply the changes (migration) using a different approach which we will discuss later!

Last updated