Entity Framework EntityKey object

What is an EntityKey ?
In a relational database we use primary keys to uniquely identify each record in the database table. Similarly, the primary key of an entity is called EntityKey and it uniquely identifies an entity. Every entity in an EDM contains an EntityKey which comprises of one or more scalar properties. These EntityKeys are used in applications to keep track of entities. A sample Entity Data Model with the name SOMModel.edmx is displayed in the designer window is shown below.


EDM of Sales Order Management system

If you observe the Conceptual Schema of the EDM in the designer view of the .edmx file, you will see the EntityContainer, EntitySets and Entities are defined as meta data. Select the .edmx file and open it using XML editor. The designer view of the .edmx file is shown in the picture below.

.edmx file in designer view

In the CSDL file which is listed below, the EntityType element describes the structure of an entity. An Entity has one or more properties and these are defined by Property element. Similar to an unique key which is used to identify a row in a table, EntityType also defines a key using one or more properties using Key element. If the key for the entity is defined using more than one property, it is called composite entity key. This key uniquely identifies an entity within the entity collection (EntitySet) and is represented as EntityKey. So, Customer entity type has a key that is based on CustomerID property of the entity.

CSDL file code

If you open the property window for the CustomerID property as shown below, the value of Entity Key property will be True. This property uniquely identifies the customer instance in the EntitySet.

CustomerID property window

How to get entity key and its value using EntityObject.EntityKey Property
At the time of materializing the entity objects, the entity key is materialized into an instance of the EntityKey class by the Entity Framework. We can access this EntityKey from the EntityKey property of the entity object. Using EntityKey Class, we can access the following information.

  • EntityContainerName
  • EntityKeyValues
  • EntitySetName
The following code sample demonstrates how to retrieve EntityContainerName, EntityKeyValues and EntitySetName using EntityKey property, the screen output is given below.

EntityKey property example code

EntityKey property example screen output

Using EntityKeyValues property, we can retrieve key names and values of EntityKey of an entity. Note that EntityKeyValues property is an IEnumerable collection. We first get EntityKey Name and Value for an Entity using the following statement.

EntityKeyValues property example code