Primary Key and Composite Primary Key using Entity Framework Core Fluent API

Primary Key and Composite Primary Key using Entity Framework Core Fluent API

In this article, I will discuss Configuring Primary Key and Composite Primary Key using Entity Framework Core (EF Core) Fluent API with Examples. Please read our previous article discussing Entity Configurations using Entity Framework Core Fluent API with Examples. At the end of this article, you will understand the following pointers.

  1. Property Configurations using Entity Framework Core Fluent API
  2. Configuring a Single Primary Key using EF Core Fluent API
  3. Switching off Identity for Numeric Primary Key using EF Core Fluent API
  4. Configuring a Composite Primary Key using EF Core Fluent API
  5. Creating Primary Key on String Property using EF Core Fluent API
Property Configurations using Entity Framework Core Fluent API

In Entity Framework Core (EF Core), we can also use the Fluent API to configure various aspects of the properties of an entity to map it with the database column in the database. Using EF Core Fluent API, we can change the corresponding column name, data type, and size. We can also configure whether the column will be Null or NotNull. It is also possible to configure the PrimaryKey, ForeignKey, concurrency column, etc., in the database using Entity Framework Core Fluent API Property Configurations.

Configuring Primary Key and Composite Primary Key using EF Core Fluent API

In Entity Framework (EF) Core, you can configure primary keys for your entities using the Fluent API. You can define a single primary key or a composite primary key (a primary key consisting of multiple columns). To understand How to Configure the Primary Key and Composite Primary Key in Entity Framework Core using Fluent API, we will use the following Student Entity.

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

Let us understand how to Configure Primary Key and Composite Primary Key using Entity Framework Core Fluent API with an example. If you see our Student domain class, it does not have either Id or <Entity Name>+ Id property. The Entity Framework Core will not follow the default code-first conventions while generating the database tables. So, in situations like this, we can go with Entity Framework Core Fluent API and configure the key property using the HasKey() method.

Configuring a Single Primary Key using EF Core Fluent API:

To configure a single primary key for an entity, we need to use the HasKey method in the OnModelCreating method of our DbContext class. For a better understanding, please modify the context class as follows. Here, we have marked the StudentRegdNumber property of the Student Entity as the Primary key using the HasKey EF Core Fluent API method. When the Primary key (Not Composite Primary Key) is created on integer data type, it will be created as an Identity column in the database.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Configure Primary Key using HasKey method
            modelBuilder.Entity<Student>().HasKey(s => s.StudentRegdNumber);
        }

        public DbSet<Student> Students { get; set; }
    }
}

With the above changes, 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 EFCoreDBMig1. The name that you are giving it should not be given earlier.

Configuring a Single Primary Key using EF Core Fluent API

Now, if you verify the database and check the Primary Key column, you can see StudentRegdNumber will be created as the Primary key, as shown in the below image.

Configuring Primary Key and Composite Primary Key using EF Core Fluent API

Switching off Identity for Numeric Primary Key using EF Core Fluent API:

In Entity Framework Core, we can configure a numeric primary key column not to use the identity/auto-increment feature. The Identity column will be generated for the Integer Type key only. If we want to provide the values for the Primary Key column explicitly, we need to switch off the identity. To do this using the Fluent API, we need to specify that the column should not be generated as an identity column. We can achieve this by using the ValueGeneratedNever method.

In our DbContext class, we must use the Fluent API in the OnModelCreating method to configure the primary key column. So, modify the context class as follows. Here, we specify the primary key for the Student entity using the HasKey method. We then configure the StudentRegdNumber property not to be generated as an identity column by using the ValueGeneratedNever method.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Configure Primary Key using HasKey method
            modelBuilder.Entity<Student>().HasKey(s => s.StudentRegdNumber);

            //Switching off Identity for StudentRegdNumber Column
            modelBuilder.Entity<Student>()
                .Property(p => p.StudentRegdNumber)
                .ValueGeneratedNever(); // Turn off identity/auto-increment
        }

        public DbSet<Student> Students { get; set; }
    }
}

This configuration tells EF Core not to generate values for the StudentRegdNumber column, and it will be our responsibility to provide unique values when inserting new records. This can be useful when we have an existing database with specific primary key values that we want to manage manually.

Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project. This is because we are going to update the Identity Column.

With the above changes, 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 EFCoreDBMig1. The name that you are giving it should not be given earlier.

Switching off Identity for Numeric Primary Key using EF Core Fluent API

Next, to test whether Identity is off, add two new entities into the Students table with user-defined values for the Primary key column. So, modify the Main method of the Program class as follows:

using EFCoreCodeFirstDemo.Entities;
namespace EFCoreCodeFirstDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //Create a Few Students with Explicit StudentRegdNumber values
                Student std1 = new Student()
                {
                    StudentRegdNumber = 101,
                    StudentRollNumber = 5001,
                    FirstName = "Pranaya",
                    LastName = "Rout"
                };

                Student std2 = new Student()
                {
                    StudentRegdNumber = 102,
                    StudentRollNumber = 5011,
                    FirstName = "Hina",
                    LastName = "Sharma"
                };

                //Create the Context Object
                using var context = new EFCoreDbContext();

                //Add both the Student Entities to the Context Object
                context.Add(std1);
                context.Students.Add(std2);

                //Call the Save Changes Method to add these two entities into the Students database table
                context.SaveChanges();

                Console.WriteLine("Student Addedd");

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}"); ;
            }
        }
    }
}

Now, run the application and verify the Students database table, and you should see the following two records in the database with the explicitly provided StudentRegdNumber.

Configuring Primary Key and Composite Primary Key using Entity Framework Core (EF Core) Fluent API with Examples

Configuring a Composite Primary Key using EF Core Fluent API:

Configuring a composite primary key (a primary key consisting of multiple columns) is also possible using the Entity Framework Core Fluent API HasKey method. In this case, we need to create an anonymous object, and using lambda expression, we need to specify multiple properties. For a better understanding, please modify the context class as follows. Here, we are making the Primary key with the combination of the StudentRegdNumber and StudentRollNumber properties of the Student Entity. In the case of composite primary, it will not create an identity column.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Configure composite primary key using HasKey method
            modelBuilder.Entity<Student>()
                .HasKey(s => new { s.StudentRegdNumber, s.StudentRollNumber });
        }

        public DbSet<Student> Students { get; set; }
    }
}

In this example, the Student entity has a composite primary key consisting of two properties: StudentRegdNumber and StudentRollNumber.

Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project as we modify the Primary key and Identity column.

With the above changes, 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 EFCoreDBMig1. The name that you are giving it should not be given earlier.

Configuring a Composite Primary Key using EF Core Fluent API

Now, if you verify the database, you should see the Primary key created on both the StudentRegdNumber and StudentRollNumber columns of the Students table in the database, as shown in the image below.

Primary Key and Composite Primary Key using Entity Framework Core (EF Core) Fluent API

Creating Primary Key on String Property using EF Core Fluent API:

It is possible to make String Property as a Primary key column using EF Core Fluent API. In this case, it will create the column as the primary key column in the database, but without identity. Let us first update the Student Entity as follows. As you can see, we have created StudentRegdNumber as a string property, and we also want to mark this property as our Primary Key column in the database.

namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public string StudentRegdNumber { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Now, modify the context class as follows. Here, we are making the FirstName Property of the Student Entity as the Primary Key column in the database. In our DbContext class, we need to use the Fluent API in the OnModelCreating method to configure the primary key for the entity.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Configure composite primary key using HasKey method
            modelBuilder.Entity<Student>()
                .HasKey(s => s.StudentRegdNumber); //Configure 'StudentRegdNumber' as the primary key
        }

        public DbSet<Student> Students { get; set; }
    }
}

With this configuration, EF Core will treat the StudentRegdNumber property as the primary key when generating the database schema. It’s important to note that string primary keys are supported in EF Core, but you should ensure that the values you assign to this property are unique, as primary keys must be unique within the table to maintain database integrity.

Note: Before Proceeding further, let us delete the EFCoreDB database using SSMS and Migration folder from our project as we modify the Primary key and Identity column.

With the above changes, 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 EFCoreDBMig1. The name that you are giving it should not be given earlier.

Creating Primary Key on String Property using EF Core Fluent API

If you verify the database, you should see the Primary key created on the StudentRegdNumber column of the Students table in the database, which type is nvarchar, as shown in the image below.

Creating Primary Key on String Property using EF Core Fluent API

Note: Remember that a primary key uniquely identifies each row in a table, so make sure the chosen properties or combination of properties are unique within the entity. EF Core also supports conventions, so if your entity follows the convention of having a property named Id and Entity Name + ID, EF Core will automatically consider it the primary key. However, you can override this convention using the Fluent API if needed.

In the next article, I will discuss Property Configuration using Entity Framework Core Fluent API with Examples. In this article, I try to explain Configuring Primary Key and Composite Primary Key using EF Core Fluent API with Examples. I hope you enjoyed this Configuring Primary Key and Composite Primary Key using EF Core Fluent API article.

Leave a Reply

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