Introduction
Entity Key is a property (or set of properties) of the entity type to identify an object in the object context. The Entity Key must be a unique identification of the entity type instance within the entity set at runtime.
The following points must considered while creating an Entity Key:
- An Entity Key must contain a set of non nullable, primitive types and immutable properties.
- A duplicate Entity Key within an entity set is not allowed.
- The properties used to create an Entity Key for the entity type never change and also surrogate keys are not supported.
Create an Entity Key for the entity set
The Entity Key represents the key of the entity object. We can create an entity using one of two methods.
1. Using CreateEntityKey method of Object Context
The "CreateEntityKey" method creates the Entity Key for the given object. If the Entity Key does not exist for the entity then this method creates a new key for that entity.
The "CreateEntityKey" method has the following two parameters:
- EntitySetName : The name of the entity set
- Entity: The object for which the key is being generated
Example
Suppose I have two tables, MasterTable and DetailTable. The relation between the tables and primary key detail is shown in the following figure.
- using (Entities context = new Entities())
- {
- MasterTable m = new MasterTable();
- m.MasterId = 1;
- EntityKey key = context.CreateEntityKey("MasterTables", m);
- object data;
- context.TryGetObjectByKey(key, out data);
- }
2. By Creating an instance of Entity Key
If we want to create an Entity Key using an instance method then we need to assign the three properties, EntityContainerName, EntitySetName and EntityKeyValues to the Entity Key object. EntityContainerName is the name of the entity container for the entity to which the Entity Key belongs. EntitySetName is the name of the entity set to which the Entity Key belongs. EntityKeyValues is an array of key values associated with Entity Key.
Example


Comments
Join the conversation! Your thoughts help the community grow.