EF Core
Getting started with EF Core
Getting started with EF Core
  • Introduction
    • What is an ORM
    • Entity Framework Core
    • EF Core architecture
    • EF Core Approaches
  • Basics of EF Core
    • Create the project
      • Create the model & context
    • Create migration
    • CRUD using EF
      • Creating many entities
      • Update & Delete
    • Adding a property
      • Add migration
  • Entity Relationships
    • Add related entity
      • Add Vehicle
      • Modify Student
      • Modify context
      • Add migration
    • Manipulate related data
  • Entity Configuration
    • Fluent APIs
      • Frequently used APIs
    • Data Annotations
      • Frequently used annotations
Powered by GitBook
On this page
  • let's add a migration
  • let us apply the migration
  1. Entity Relationships
  2. Add related entity

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

PreviousModify contextNextManipulate related data

Last updated 2 years ago