Key Attribute in Entity Framework Core

Key Attribute in Entity Framework Core (EF Core)

In this article, I will discuss Key Data Annotation Attributes in Entity Framework Core (EF Core) with Examples. Please read our previous article, discussing the Column Data Annotation Attribute in Entity Framework Core with Examples. At the end of this article, you will understand the following pointers.

  1. What is the Primary Key in the Database?
  2. What is the Key Attribute in Entity Framework Core?
  3. Examples to Understand the Key Attribute in EF Core
  4. How to Make Composite Primary Key in Entity Framework Core?
  5. When to use Key Attribute in EF Core?
  6. Can we Create a Primary Key on String Property using Entity Framework Core?
What is the Primary Key in the Database?

The Primary Key is the combination of Unique and NOT NULL Constraints. That means it will neither allow 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 on single or multiple columns, i.e., the composite primary key is also possible. A table must have a primary key to identify each record uniquely. Entity Framework Core will throw an error while creating or updating the database if we don’t specify the Primary Key Property.

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 it will also 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.cs, as follows. Here, we are adding the Student entity as a DbSet Property and providing the property name as Students, so 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 using Package Manager Console or .NET Core CLI.

So, open the Package Manager Console and Execute the add-migration and update-database commands as follows. 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, 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 the Package Manager Console and Execute the add-migration command.

Key Data Annotation Attribute in EF Core

As you can see in the above image, executing the add-migration command throws 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 Error?

How to overcome the above error 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. If you go to the definition of Key Attribute, then you will see the following. It is a sealed 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 the System.ComponentModel.DataAnnotations namespace, so include that namespace as well. The key Attribute will mark the StudentRegdNo property as the key property, and the entity framework core will generate the Primary key for the StudentRegdNo property in the database.

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, open the Package Manager Console and Execute the add-migration and update-database commands as follows.

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 uniquely identifying 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 not 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 to make a Composite Primary Key. This PrimaryKey attribute can be used for both keys of a single property and composite keys of multiple properties. If you go to the definition of PrimaryKey Attribute, then you will see the following. It is a sealed class having one constructor, which takes two parameters. The first parameter is the string property name, and the second parameter is the optional params array. Using this optional params array, we can specify other property names.

Key Data Annotation Attribute in Entity Framework Core with Examples

Note: You cannot apply this Attribute on an already created database table, and if you try, you will get the following error. The [PrimaryKey] attribute was introduced in EF Core 7.0. Use Fluent API in older versions. The Composite primary keys are configured by placing the [PrimaryKey] attribute on the entity type class.

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

To simplify things, let us first delete the EFCoreDB database from the SQL Server 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, open the Package Manager Console and Execute the add-migration and update-database commands as follows.

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, provided the column is of integer type. However, creating a Composite Primary Key will not mark the primary key columns as identity columns.

Can we Create a Primary Key on String Properties using EF Core?

Yes, we can also create the Primary key on a string property or properties. For a better understanding, modify the Student entity as follows. As you can see, here we have created the StudentId property with the string data type, and EF core will mark this property as the Primary Key in the database. But this will not be marked as an Identity column.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public string StudentId { get; set; }
        public string SerialNo { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

We can also create a composite Primary Key using string properties. For a better understanding, modify the Student entity as follows. As you can see, we have marked the RegdNo and SerialNo properties as String type, and then we create a composite primary key based on these two properties, and it will work.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    [PrimaryKey(nameof(RegdNo), nameof(SerialNo))]
    public class Student
    {
        public string RegdNo { get; set; }
        public string SerialNo { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}
When to use Key Attribute in EF Core?

In EF Core, entities have a primary key that uniquely identifies each record in a table. The [Key] attribute indicates which property or properties make up the primary key. By default, EF Core assumes that the property named Id or <ClassName>Id serves as the primary key, but the [Key] attribute provides an explicit way to specify this. Primary keys are crucial in relational databases for identifying records in a table in a unique way. We need to use the [Key] attribute,

  • When EF Core’s convention does not correctly identify the primary key property.
  • When working with existing databases where primary key columns might have non-standard names.
  • When being explicit about your intentions for clarity.

The [Key] attribute provides a declarative way to specify the primary key of an entity directly within the class. If you need more advanced configurations or prefer to separate configurations from the domain classes, you can utilize the Fluent API.

In the next article, I will discuss ForeignKey Attributes in Entity Framework Core with Examples. I explain the Key Data Annotation Attribute in Entity Framework Core with Examples in this article. 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 *