Create primary key,composite key in Entity framework | Use of key attribute in ASP.Net MVC

Create primary key,composite key in Entity framework or Use of key attribute in ASP.Net MVC

Introduction:

In this tutorial i am going to explain about how to Create primary key,composite key in Entity framework or Use of key attribute . In my previous tutorial i have explained about How to create custom validation attribute in mvc 4ASP.NET MVC client side validation using data annotationsAsp.Net – How to Create Dynamic Pages & Url With C#.Net,VB.NetCRUD operations using Entity Framework Code First Approach and MVC 4 and How To Create Help Pages(Documents) For Asp.Net Web API

Implementation of Create primary key,composite key in Entity framework:

Now we will see the implementation of how to Create primary key,composite key in Entity framework | Use of key attribute in ASP.Net MVC.

By default in code first convention of entity framework primary key will be created for the class with property name as Id or property with name [Classname]Id.  For example i have created a Student class with property StudentId. Now if i run my application StudentId will be created as primary key in the database table. Below is the student class.

If you want to override this default approach or if you want to define the property as primary key that doesn’t match the naming convention you can make use of Key attribute. You can apply Key attribute to any property that you want to make as primary key. In the below sample class i have changed the StudentId as StudId and decorated the property with Key attribute. So in database StudId will be created as primary key.

Please note if you define the int property with [Key] attribute it will automatically create primary key with identity enabled.

Create composite key in Entity framework:

Now if you want to make the composite primary key (Combination of more than one column act as primary key) then we can achieve the same by using the [Key] attribute.

We need to decorate the columns with the [Key] attribute and the column order. Please find the modified complete code below.

 

Conclusion:

Hope you learned how to Create primary key,composite key in Entity framework | Use of key attribute in ASP.Net MVC.  Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Leave a Reply

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