Obtaining an ObjectKey
The purpose of this topic is to demonstrate the different ways for creating a new ObjectKey instance.
Using the ObjectKey Constructors
The most simple way 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 model. If there are more than one persistent type with the specified name in the persistent types collection of the 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.
FluentModel dbContext = new FluentModel();
ObjectKey withoutVersion = dbContext.CreateObjectKey(myEntity);
ObjectKey withVersion = dbContext.CreateObjectKeyWithVersion(myEntity);
Dim dbContext As New FluentModel()
Dim withoutVersion As ObjectKey = dbContext.CreateObjectKey(myEntity)
Dim withVersion As ObjectKey = dbContext.CreateObjectKeyWithVersion(myEntity)