In Code-First approach, we can easily create the primary key foreign key relations between database tables with Entity Framework Core.
Open Microsoft Visual Studio 2022 => open application which we created in my previous article. Here we will add AuthorId foreign key to Books table.
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string BookDesc { get; set; }
}
To add AuthorId foreign key to Books table, just add virtual property of type Author to Book class as shown below.
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string BookDesc { get; set; }
public virtual Author Author { get; set; }
}
Now create db migration by using Add-migration command in NuGet package manager console. Open tools => NuGet Package Manger => Package Manager Console.
Execute “Add-migration AddAuthorIdToBookAsFooreignKey” command under EntityFrameworkCoreExample.Data project.
It creates AddAuthorIdToBookAsFooreignKey.cs migration class in Migrations folder.
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EntityFrameworkCoreExample.Data.Migrations
{
public partial class AddAuthorIdToBookAsFooreignKey : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "AuthorId",
table: "Books",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_Books_AuthorId",
table: "Books",
column: "AuthorId");
migrationBuilder.AddForeignKey(
name: "FK_Books_Authors_AuthorId",
table: "Books",
column: "AuthorId",
principalTable: "Authors",
principalColumn: "AuthorId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Books_Authors_AuthorId",
table: "Books");
migrationBuilder.DropIndex(
name: "IX_Books_AuthorId",
table: "Books");
migrationBuilder.DropColumn(
name: "AuthorId",
table: "Books");
}
}
}
As shown above, it is going to create FK_Books_Authors_AuthorId foreign key on Books table. Run the application to affect these changes in database. After successfully running the application, it created AuthorId column with foreign key FK_Books_Authors_AuthorId on Books table as shown below.