Key Attribute in Entity Framework Core

Key Attribute in Entity Framework Core (EF Core)

In this article, I am going to discuss Key Data Annotation Attributes in Entity Framework Core (EF Core) with Examples. Please read our previous article, where we discussed the Column Data Annotation Attribute in Entity Framework Core with Examples. Before understanding the Key Attribute, let us first understand what is a Primary Key in a database.

What is Primary Key in the Database?

The Primary Key is the combination of Unique and Not Null Constraints. That means it will not allow either NULL or Duplicate values into a column or columns on which the primary key constraint is applied. Using the primary key, we can enforce entity integrity, i.e., using the primary key column value, we can uniquely identify a record.

A table should contain only 1 Primary Key, which can be either on single or multiple columns, i.e., the composite primary key is also possible. A table should and must have a primary key to identify each record uniquely. And in Entity Framework Core, if we don’t specify the Primary Key Property, then it will throw an error while creating or updating the database.

Key Attribute in Entity Framework Core

The Key Data Annotation Attribute in Entity Framework Core can be applied to a property of an entity to make it the key property, and also it will make that corresponding column the Primary Key column in the database. As per the default convention, the EF Core will create the primary key column for the property whose name is Id or <Entity Class Name> + Id (case insensitive). For instance, if the Student class has a property named id, ID, iD, Id, studentid, StudentId, STUDENTID, or sTUdentID, EF Core will create a Primary Key column in the Students table.

For example, let us modify the Student.cs class file as follows. Here, we have added the StudentId property in the Student class. So, this property will be created as a Primary Key column in the corresponding database table.

namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

Next, modify the content class, i.e., EFCoreDbContext, as follows. Here, we are adding the Student entity as a DbSet Property and providing the property name as Students so that the database will create the table with the name Students.

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; }
    }
}

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 Mg1. The name that you are giving it should not be given earlier.

Key Data Annotation Attributes in Entity Framework Core (EF Core) with Examples

Now, if you verify the database and you should see the following. As you can see, the StudentId column is created as the primary key column.

Key Data Annotation Attribute in EF Core

Now, what our business requirement is, we do not want to make StudentId or Id the Primary key column. Instead, we want a different column. Let us say StudentRegdNo as the primary key in our database. Then this default convention of EF Core will not work. Let us prove this. Let us modify the Student entity class as follows. Here, instead of StudentId, we are using the StudentRegdNo property.

namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentRegdNo { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

With the above changes, open Package Manager Console and Execute the add-migration command.

Key Data Annotation Attribute in EF Core

As you can see in the above image while executing the add-migration command, it is throwing an exception saying the entity type ‘Student’ requires a primary key to be defined. If you intend to use a keyless entity type, call ‘HasNoKey’ in ‘OnModelCreating.’

How to Overcome the Above Problem?

How to overcome the above problem means how can we make the StudentRegdNo property the key property so that EF Core will make this property the Primary Key column in the corresponding database table?

We need to use the Key Data Annotation Attribute in EF Core for this. If you go to the definition of Key Attribute, then you will see the following. It’s a class that has a parameterless constructor. The Key Attribute denotes one or more properties that uniquely identify an entity.

Key Data Annotation Attribute in EF Core with Examples

So, modify the Student class as follows. As you can see in the below code, we decorate the StudentRegdNo property with the Key Attribute. The Key Attribute belongs to System.ComponentModel.DataAnnotations namespace, so include that namespace as well.

using System.ComponentModel.DataAnnotations;
namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        [Key]
        public int StudentRegdNo { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands.

Key Data Annotation Attribute in EF Core with Examples

Now, verify the database, and you should see StudentRegdNo as the Primary Key shown in the image below.

Key Data Annotation Attribute in Entity Framework Core with Examples

Note: The Key Attribute denotes one or more properties that uniquely identify an entity. The Key attribute can be applied to a property of any primitive data type except unsigned integers.

How to Make Composite Primary Key in Entity Framework Core?

If you want to make a composite primary key using Entity Framework Core, it is impossible to use the Key Attribute. It is possible in Entity Framework but in Entity Framework Core.

In Entity Framework, the Key Attribute and the Column Data Annotation Attribute with the Column Order Property can be applied to multiple entity properties, creating a composite primary key in the corresponding database table.

In EF Core, we need to use the PrimaryKey Attribute in order to make a Composite Primary Key. This PrimaryKey attribute can be used for both keys of a single property and for composite keys of multiple properties.

Key Data Annotation Attribute in Entity Framework Core with Examples

The Composite primary keys are configured by placing the [PrimaryKey] attribute on the entity type class.

Note: You cannot apply this Attribute on an already created database table, and if you try, then you will get the following. The [PrimaryKey] attribute was introduced in EF Core 7.0. Use the Fluent API in older versions.

System.InvalidOperationException: To change the IDENTITY property of a column, the column needs to be dropped and recreated.

So, let us first delete the EFCoreDB database from the SQL Server DB using SSMS and then delete the Migration folder from our project.

Next, modify the Student Entity Class as follows. As you can see here, we have applied the PrimaryKey Attribute on the Student Entity, and to this attribute, we are passing the RegdNo and SerialNo properties.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    [PrimaryKey(nameof(RegdNo), nameof(SerialNo))]
    public class Student
    {
        public int RegdNo { get; set; }
        public int SerialNo { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

With the above changes in place, open Package Manager Console and Execute the following add-migration and update-database commands.

Key Data Annotation Attribute in Entity Framework Core

Now, verify the database, and you should see a composite primary key based on two columns, as shown in the below image.

Key Data Annotation Attribute in Entity Framework Core

Note: In Entity Framework Core, the most important point you need to remember is that if you create the Primary Key on a single column, it will also mark that column as an identity column. But creating a Composite Primary Key will not mark the primary key columns as identity columns.

In the next article, I am going to discuss ForeignKey Attributes in Entity Framework Core with Examples. In this article, I try to explain the Key Data Annotation Attribute in Entity Framework Core with Examples. I hope you enjoyed this article’s Key Data Annotation Attribute in EF Core with Examples. Please give your valuable feedback and suggestions about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *