Add migration

let's add a migration

Let us add migration to include the vehicle type as well. Before running the below command, make sure you have saved all the files and the application compiles successfully.

dotnet ef migrations add VehicleAdded

Notice the generated code in migration file

//other code...
migrationBuilder.CreateTable(
name: "Vehicles",
columns: table => new
{
    Id = table.Column<int>(type: "int", nullable: false)
        .Annotation("SqlServer:Identity", "1, 1"),
    Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
    StudentId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
    table.PrimaryKey("PK_Vehicles", x => x.Id);
    table.ForeignKey(
        name: "FK_Vehicles_Students_StudentId",
        column: x => x.StudentId,
        principalTable: "Students",
        principalColumn: "Id",
        onDelete: ReferentialAction.Cascade);
});
//other code...

Notice the following

  • A new table is being created in the name of Vehicles

    • it has the required columns along with appropriate data types

    • primary key for the vehicles table is Id column as usual

  • StudentId is made a foreign key to Students table

  • EF has identified the principal table and the principal column as Students and Id respectively

  • Delete cascade is the default action, we can configure it otherwise

  • As expected, there is no change to the Students table

let us apply the migration

Now that we have verified that the migration code generated is appropriate and matches our domain requirements, let us go ahead and apply it so that the necessary changes are made in the database

dotnet ef database update

We should now see the new table created in our database

Last updated