Back to: ASP.NET Core Tutorials For Beginners and Professionals
ForeignKey Attribute in Entity Framework Core
In this article, I am going to discuss the ForeignKey Data Annotation Attribute in Entity Framework Core (EF Core) with Examples. Please read our previous article, where we discussed the Key Attribute in Entity Framework Core with Examples. Before understanding ForeignKey Attribute in EF Core, let us first understand what is a Foreign Key in a database.
What is a Foreign Key Constraint in a Database?
Creating relationships between database tables is a crucial concept in managing databases. This mechanism facilitates the linking of data stored in various tables, making retrieving information easier and more efficient.
To connect two database tables, a Foreign Key must be specified in one table that references a unique column (either a Primary Key or Unique Key) in the other table. This constraint binds the two tables together and verifies the presence of data from one table in the other. A Foreign Key in one table points to a primary or unique key in another table.
ForeignKey Attribute in Entity Framework Core:
In EF Core, the ForeignKey Attribute is used to configure the relationship between two entities. This attribute takes precedence over EF Core’s default foreign key convention, which is followed otherwise. By default, Entity Framework Core searches for a foreign key property in the dependent entity with the same name as the primary key property in the principal entity.
In Entity Framework Core, a Relationship always involves two endpoints. Each endpoint must provide a navigational property that maps to the other end of the relationship. To illustrate this, consider the following Standard Entity, which serves as our Principal Entity, with StandardId as the Primary Key Property. Note that we have a mandatory collection navigational property called “students” that is necessary for implementing Foreign Key Relationships using EF Core.
namespace EFCoreCodeFirstDemo.Entities { public class Standard { public int StandardId { get; set; } public string? StandardName { get; set; } public string? Description { get; set; } public ICollection<Student>? Students { get; set; } } }
Next, modify the Student Entity as follows. Note that we have included the StandardId property, which corresponds to the Primary Key Property of the Standard table. Additionally, we have included the Standard Reference Navigational Property, which is essential for establishing the Foreign Key in the Student database table.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } //The Following Property Exists in the Standard Entity public int StandardId { get; set; } //To Create a Foreign Key it should have the Standard Navigational Property public Standard? Standard { get; set; } } }
In our example, we’ll be demonstrating the one-to-many relationship between the Student and Standard Entities. This relationship is represented by including a property called StandardId in the Student class, which has a reference property called Standard. Meanwhile, the Standard entity class includes a collection navigation property called Students. The StandardId property in the Student Class matches with the primary key property of the Standard class. As a result, the StandardId property in the Student class will automatically become a foreign key property, and the corresponding column in the database table will also become a foreign key column.
Note: You need to remember that both Entities should and must have Navigational Properties to implement Foreign Key Relationships. In our example, Student Entity has the Standard Reference Navigational Property, and Standard Entity has the Students collection Navigation Property which will establish the one-to-many relationship between these two entities. That means one student has one standard, and one standard can have multiple students.
Next, modify the context class as follows:
using Microsoft.EntityFrameworkCore; namespace EFCoreCodeFirstDemo.Entities { public class EFCoreDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Student>Students { get; set; } public DbSet<Standard> Standards { get; set; } } }
Note: Please delete the EFCoreDB database from the SQL Server DB using SSMS if it already exists, and then also delete the Migration folder from your project if it exists.
As we already discussed, whenever we add or update domain classes or configurations, we need to sync the database with the model using add-migration and update-database commands either using Package Manager Console or .NET Core CLI.
So, open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving DbMig1. The name that you are giving it should not be given earlier.
If you verify the database, the Foreign key should have been created in the Student database, as shown in the image below. Here, you can see the Foreign Key Property is created with the name StudentId.
If the Foreign Key Property does not exist in the Dependent Entity class, then Entity Framework will create a Foreign Key column in the Database table with the Primary Key Property Name of the Principal Entity.
To understand this, modify the Student Entity class as follows. Here, you can see we have not added the StandardId property. So, in this case, Entity Framework will create the Foreign Key with the name StandardId. We must have added the Standard Property. Otherwise, the foreign key will not be created.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } //To Create a Foreign Key it should have the Standard Navigational Property public Standard? Standard { get; set; } } }
With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands as shown below.
If you verify the database, the Foreign key should have been created in the Student database table with StudentId, as shown in the image below.
These are the default conventions which is followed by Entity Framework to create the Foreign Key column in the database.
What is ForeignKey Attribute in Entity Framework?
The ForeignKey Attribute in Entity Framework Core is used to configure a foreign key relationship between the entities. It overrides the default foreign key convention, which is followed by EF Core. It allows us to specify the foreign key property in the dependent entity whose name does not match the primary key property of the principal entity.
Now, if you go to the definition of ForeignKey Attribute, then you will see the following signature. As you can see, this class has one constructor that takes the associated navigation property’s name or one or more associated foreign keys as an input parameter.
The [ForeignKey(name)] attribute can be applied in three ways:
- [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity.
- [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.
- [ForeignKey(ForeignKeyPropertyName)] on the navigation property in the principal entity.
Note: Before proceeding further, first of all, we need to identify the Principal Entity and the Dependent Entity. In our example, the Standard is the Principal Entity, and the Student is the Dependent Entity; we will create the Foreign Key in the Dependent Entity.
[ForeignKey] on the Foreign Key Property in the Dependent Entity
The [ForeignKey] Attribute in Entity Framework Core can be applied to the foreign key property in the Dependent Entity, and the related navigation property name (in this case, Standard) can be specified as a parameter. For a better understanding, please modify the Student Entity as follows.
using System.ComponentModel.DataAnnotations.Schema; namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } [ForeignKey("Standard")] public int StandardReferenceId { get; set; } //Related Standard Navigational Property public Standard? Standard { get; set; } } }
With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands as shown below.
If you verify the database, the foreign key should have been created in the Student database table with StandardReferenceId, as shown in the image below.
[ForeignKey] on the Navigation Property in the Dependent Entity
The [ForeignKey] Attribute in EF Core can also be applied to the Navigation Property, and in this case, we need to specify the related foreign key property name in the [ForeignKey] Attribute. For a better understanding, please modify the Student Entity as follows.
using System.ComponentModel.DataAnnotations.Schema; namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } //Related Foreign Key Property public int StandardReferenceId { get; set; } [ForeignKey("StandardReferenceId")] public Standard? Standard { get; set; } } }
In the above example, the [ForeignKey] attribute is applied on the Standard navigation property, and the name of the foreign key property StandardReferenceId is specified. Here, Entity Framework Core will create the foreign key column StandardReferenceId in the Students table in the database.
With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands as shown below.
If you verify the database, the foreign key should have been created in the Student database table with StandardReferenceId, as shown in the image below.
[ForeignKey] on the Navigation Property in the Principal Entity
The [ForeignKey] Attribute in EF Core can also be applied to the Navigation Property in the Principal Entity, and the related foreign key property name can be specified in the Dependent Entity. Let us understand this with an example. First, modify the Student Entity as follows. Here, you can see we have removed the ForeignKey Attribute.
namespace EFCoreCodeFirstDemo.Entities { public class Student { public int StudentId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } public int StandardReferenceId { get; set; } public Standard? Standard { get; set; } } }
Now, we want the Property StandardReferenceId to be created as a Foreign Key column in the Students database table which must be pointed to the StandardId Property of the Standard entity. To do so, modify the Standard Entity as follows. Here, you can see the [ForeignKey] attribute is applied on the Students collection navigation property, and here we are passing the StandardReferenceId property to the [ForeignKey] attribute, which will make the StandardReferenceId a Foreign Key Property.
using System.ComponentModel.DataAnnotations.Schema; namespace EFCoreCodeFirstDemo.Entities { public class Standard { public int StandardId { get; set; } public string? StandardName { get; set; } public string? Description { get; set; } [ForeignKey("StandardReferenceId")] public ICollection<Student>? Students { get; set; } } }
With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands as shown below.
If you verify the database, the foreign key should have been created in the Student database table with StandardReferenceId, as shown in the image below.
Note: In our upcoming articles, I am going to discuss One-to-One, One-to-Many, and Many-to-Many Relationships in detail using Entity Framework Core.
In the next article, I am going to discuss Index Attributes in Entity Framework Core with Examples. Here, in this article, I try to explain the ForeignKey Data Annotation Attribute in Entity Framework Core with Examples. I hope you enjoyed this ForeignKey Attribute in EF Core with Examples article. Please give your valuable feedback and suggestions about this article.