Data Annotations Key Attribute in Entity Framework

The Key Attribute or Primary key attribute maps the property as the primary key column in the database. We can also use it to create a composite Primary key.

Default Convention

Entity Framework Default conventions look for the property with the name id or with the name  <className>ID. It then maps that property to the Primary Key. In case it finds both id property and  <className>ID property, then id property is used. The following model creates the table with CustomerID As the primary key.

Primary Key Default Convention in Entity Framework
Primary Key Default Convention

Key Attribute

You can override this behavior using the Data Annotation Key attribute. Entity Framework Data Annotation Key attribute marks the property as Primary Key. This will override the default Primary Key. The following code creates the table with CustomerNo as the Primary key instead if CustomerID

Do not forget to import the following namespace

Key Attribute in Entity Framework
Key Attribute in Entity Framework

Note that the CustomerNo column created with the Identity enabled. Key attribute, if applied on the integer column will create the column with the Identity enabled (autoincrement)

The unsigned data types (uint) are not allowed in EF as Primary key. Infact Entity Framework does not support unsigned data types

Key Attribute on a string property

Key Attribute on string data type in Entity Framework
Key Attribute on string data type in Entity Framework

Enabling / Disabling identity column

You can disable/enable the identity on the numeric column by using the DatabaseGenerated attribute.

The following code disables the identity column

Key Attribute with identity disabled
Key Attribute on in with identity disabled

The following code enables the identity column

Composite Primary Key

When Primary Key consists of more than on Property it is called a Composite primary key. We can apply the Key attribute on all the candidate fields to denote them as Composite Key. In such a case we must also specify the Column Order of the appearance of the key.

Composite Primary Key Attribute in entity framework
Composity Primary Key Attribute in entity framework

If you do not specify the Column Order Attribute, then the entity framework will raise the error “Unable to determine composite primary key ordering for type”

Few important notes on Composite Primary key

  1. You can use any integer values in order attribute. For example, 10 and 15 are perfectly acceptable instead of 1 and 2.
  2. If we apply Composite Key on integer or GUID columns, it does not create an Identity column.
  3. There is no restriction on the data type of the key except for the unsigned data types

References

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top