Key Element (CSDL)

The Key element is a child element of the EntityType element and defines an entity key (a property or a set of properties of an entity type that determine identity). The properties that make up an entity key are chosen at design time. The values of entity key properties must uniquely identify an entity type instance within an entity set at run time. The properties that make up an entity key should be chosen to guarantee uniqueness of instances in an entity set. The Key element defines an entity key by referencing one or more of the properties of an entity type.

The Key element can have the following child elements:

Applicable Attributes

Any number of annotation attributes (custom XML attributes) may be applied to the Key element. However, custom attributes may not belong to any XML namespace that is reserved for CSDL. The fully-qualified names for any two custom attributes cannot be the same.

Example

The example below defines an entity type named Book. The entity key is defined by referencing the ISBN property of the entity type.

<EntityType Name="Book">
  <Key>
    <PropertyRef Name="ISBN" />
  </Key>
  <Property Type="String" Name="ISBN" Nullable="false" />
  <Property Type="String" Name="Title" Nullable="false" />
  <Property Type="Decimal" Name="Revision" Nullable="false" Precision="29" Scale="29" />
  <NavigationProperty Name="Publisher" Relationship="BooksModel.PublishedBy"
                      FromRole="Book" ToRole="Publisher" />
  <NavigationProperty Name="Authors" Relationship="BooksModel.WrittenBy"
                      FromRole="Book" ToRole="Author" />
</EntityType>

The ISBN property is a good choice for the entity key because an International Standard Book Number (ISBN) uniquely identifies a book.

The following example shows an entity type (Author) that has an entity key that consists of two properties, Name and Address.

<EntityType Name="Author">
  <Key>
    <PropertyRef Name="Name" />
    <PropertyRef Name="Address" />
  </Key>
  <Property Type="String" Name="Name" Nullable="false" />
  <Property Type="String" Name="Address" Nullable="false" />
  <NavigationProperty Name="Books" Relationship="BooksModel.WrittenBy"
                      FromRole="Author" ToRole="Book" />
</EntityType>

Using Name and Address for the entity key is a reasonable choice, because two authors of the same name are unlikely to live at the same address. However, this choice for an entity key does not absolutely guarantee unique entity keys in an entity set. Adding a property, such as AuthorId, that could be used to uniquely identify an author would be recommended in this case.

See Also

Concepts

Entity Framework Overview
CSDL Specification
Schema Element (CSDL)

Other Resources

CSDL, SSDL, and MSL Specifications
ADO.NET Entity Data Model Tools
entity key (Entity Data Model)