Back to: Entity Framework Tutorials For Begineers and Professionals
Key Attribute in Entity Framework with Examples
In this article, I am going to discuss Key Data Annotation Attributes in Entity Framework Code First Approach with Examples. Please read our previous article where we discussed Column Data Annotation Attribute in Entity Framework Code First Approach with Examples. Before understanding Key Attributes, 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 value we should 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. A table should have a primary key to uniquely identify each record.
Key Attribute in Entity Framework
The Key attribute in Entity Framework Code First Approach can be applied to a property in an entity class to make it as the key property and also it will make that corresponding column as the PrimaryKey column in the database. As per the default convention, the Entity Framework will create the primary key column for the property whose name is Id or <Entity Class Name> + “Id” (case insensitive). For example, let us modify the Student entity class as follows. Here, we have created the StudentId property in the Student class. So, this property will be created as a Primary Key column in the corresponding database table.
using System; using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
As we are going to update the Entity Models many times, in order to avoid the Run Time Exception when the model changes and when we rerun the application, let us set the database initializer as DropCreateDatabaseIfModelChanges. So, modify the context class as follows:
using System.Data.Entity; namespace EFCodeFirstDemo { public class EFCodeFirstContext : DbContext { public EFCodeFirstContext() : base("name=MyConnectionString") { //Setting the Database Initializer as DropCreateDatabaseIfModelChanges Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFCodeFirstContext>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public DbSet<Student> Students { get; set; } } }
Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.
Now, modify the Main method of the Program class as follows. Here, we are adding one student entity to the database.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var student = new Student() { FirstName = "Pranaya", LastName = "Rout" }; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); Console.ReadKey(); } } } }
With the above changes in place, now run the application and verify the database and you should see the following. As you can see, the StudentId column is created as the primary key column.
Now, we do not want to make StudentId as the Primary key column, instead, we want a different column let us say StudentRegdNo as the primary key. Then this will not work with the default convention which is followed by Entity Framework Code First Approach. Let us prove this. Let us modify the Student domain class as follows. Here, instead of StudentId, we are using the StudentRegdNo property.
using System; using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { public int StudentRegdNo { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
With the above changes in place, now run the application code again and this time it will throw the following runtime error saying that No Key has been defined for the Entity Student as shown in the below image.
How to overcome the above problem?
How to overcome the above problem means how can we make the StudentRegdNo a key property which should make this the Primary Key column in the corresponding database table. For this, we need to use the Key Data Annotation attribute. 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.
So, modify the Student class as follows. As you can see in the below code, we just decorate the StudentRegdNo property with the Key Attribute.
using System.ComponentModel.DataAnnotations; namespace EFCodeFirstDemo { 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, now run the application code again, and this time you will not get any exceptions and the database should be updated as expected. You can also verify the database as shown in the below image.
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?
In Entity Framework, the Key Data Annotation Attribute along with the Column Data Annotation Attribute with the Column Order Property can be applied to multiple properties of an entity which will create a composite primary key in the corresponding database.
For a better understanding, please modify the Student Entity Class as follows. As you can see here, we have applied the Key Attribute with the StudentRegdNo and StudentSerialNo properties. Further, you can notice we have applied the Column Attribute with the Order Property and this is mandatory. If you omit the order then you will get a runtime exception.
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { [Key] [Column(Order =1)] public int StudentRegdNo { get; set; } [Key] [Column(Order = 2)] public int StudentSerialNo { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
With the above changes in place, now run the application code and this time it will create a composite primary key based on two columns. You can also verify the database as shown in the below image.
Note: In Entity Framework, the most important point that you need to remember is the Key Data Annotation Attribute creates a Primary Key with an identity column when applied to a single integer type property. But it will not create the Identity column in the case of a composite primary key.
In the next article, I am going to discuss ForeignKey Attributes in Entity Framework Code First Approach with Examples. Here, in this article, I try to explain Key Data Annotation Attribute in Entity Framework Code First Approach with Examples. I hope you enjoyed this Key Data Annotation Attribute in Entity Framework Code First Approach with Examples article. Please give your valuable feedback and suggestions about this article.