Obtaining an ObjectKey
This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.
The purpose of this topic is to demonstrate the different ways for creating a new ObjectKey instance.
Using the ObjectKey Constructors
The most simple to create a new instance of the ObjectKey class is to instantiate it directly. You need to specify the persistent type name and key-value pairs. The type name can be the simple name, full name or assembly qualified name of the persistent type.
The type name should uniquely identify a persistent type within the domain model. If there are more than one persistent type with the specified name in the persistent types collection of the domain model, then an ArgumentException will be thrown when you try to obtain an object.
ObjectKey objectKey = new ObjectKey("MyEntity", new[] { new ObjectKeyMember("Id", 1) });
Dim _objectKey As New ObjectKey("MyEntity", { New ObjectKeyMember("Id", 1) })
Using the Static Create() and CreateWithVersion() Methods
An ObjectKey for a persistent object can be obtained using the static Create or CreateWithVersion methods of the ObjectKey class. ObjectKey for an object added to the context or deleted from the context but not yet committed to the database (via the SaveChanges method), does not have any version information. Note, that obtaining an ObjectKey with version information might cause a query to be executed against the database.
ObjectKey withoutVersion = ObjectKey.Create(myEntity);
ObjectKey withVersion = ObjectKey.CreateWithVersion(myEntity2);
Dim withoutVersion As ObjectKey = ObjectKey.Create(myEntity)
Dim withVersion As ObjectKey = ObjectKey.CreateWithVersion(myEntity2)
Using the OpenAccessContext.CreateObjectKey() and OpenAccessContext.CreateObjectKeyWithVersion() Methods
Alternatively, you could use the CreateObjectKey and CreateObjectKeyWithVersion methods exposed by the OpenAccessContext.
EntitiesModel dbContext = new EntitiesModel();
ObjectKey withoutVersion = dbContext.CreateObjectKey(myEntity);
ObjectKey withVersion = dbContext.CreateObjectKeyWithVersion(myEntity);
Dim dbContext As New EntitiesModel()
Dim withoutVersion As ObjectKey = dbContext.CreateObjectKey(myEntity)
Dim withVersion As ObjectKey = dbContext.CreateObjectKeyWithVersion(myEntity)