Retrieving a single entity with GetObjectByKey method of ObjectContext using EntityKey
The GetObjectByKey method of ObjectContext returns an entity object based on a specific EnityKey. We need to pass EntityKey which represents the key of the entity as a parameter to the GetObjectByKey method. This method first attempts to retrieve the matched entity without constructing a query from the context (ObjectStateManager) and if it does not exist, it will execute query and retrieves entity from the database. The EntityKey object can be instantiated by passing three parameters to the EntityKey class.
The first statement in the code creates an EntityKey. The three parameters are EntitySet - Customers, key property name - CustomerID and value of the Key property which is 16. The GetObjectByKey method of ObjectContext takes the EntityKey as parameter and returns the object from the ObjectStateManager, if it exists; otherwise it is retrieved from the database.
The advantage of using this method is that if the object already exists in the context, there will be no attempt to access the database, and one round trip to the database is avoided.
The disadvantage of using GetObjectByKey method is that this method returns the object and it should be casted to an actual entity type, in this case Customer (as shown in the above code example).
Comparison between GetObjectByKey methods with TryGetObjectByKey method Which method is to be used is a common question programmers ask. The answer is, if the matching entity does not exist in ObjectStateManager or in the database, exception occurs. TryGetObjectByKey method can handle this situation.
Comparison between GetObjectByKey method with GetObjectStateEntry() method
The below code demonstrates how to use GetObjectStateEntry method to retrieve single entity.
Comparison between GetObjectByKey method with First operator
Even though both methods retrieve an object, the First() method will not check whether the requested entity is already exists in the context, simply query the database and returns the object as shown below. But using GetObjectByKey method, we can avoid extra round trip to the database because this method checks the context before executing query to the database.
The below code demonstrates how to use First() method to retrieve a single entity.
Using GetObjectByKey method for deleting entities
The following code demonstrates how to delete an entity.
In the above code, the DeleteObject() method marks the entity as deleted. In fact, the state of an entity in ObjectStateEntry object is marked as Deleted. When SaveChanges() method is invoked, the DELETE command is executed and the row is deleted from the database. That means, to use DeleteObject() method we need the entity to be deleted. If the entity is already retrieved and present in the context, it is fine. But sometimes you may want to delete data and knowing only the key value of the entity. In this situation GetObjectByKey method is used. The following code demonstrates this. The EntityKey class creates the EntityKey with the specified EntitySet, key property name and value of the key.
Compare the code block1 and this code block. We have already discussed that the GetObjectByKey() method returns object instance (in the code block 1). We have casted to a correct entity type to display or further operation. But in this case, we are just deleting it. So, we have not done any casting. In the above code, GetObjectByKey method looks for entity in context and retrieves the database and gets the object.
The first statement in the code creates an EntityKey. The three parameters are EntitySet - Customers, key property name - CustomerID and value of the Key property which is 16. The GetObjectByKey method of ObjectContext takes the EntityKey as parameter and returns the object from the ObjectStateManager, if it exists; otherwise it is retrieved from the database.
The advantage of using this method is that if the object already exists in the context, there will be no attempt to access the database, and one round trip to the database is avoided.
The disadvantage of using GetObjectByKey method is that this method returns the object and it should be casted to an actual entity type, in this case Customer (as shown in the above code example).
Comparison between GetObjectByKey methods with TryGetObjectByKey method Which method is to be used is a common question programmers ask. The answer is, if the matching entity does not exist in ObjectStateManager or in the database, exception occurs. TryGetObjectByKey method can handle this situation.
Comparison between GetObjectByKey method with GetObjectStateEntry() method
- GetObjectByKey method takes EntityKey as parameter and returns the complete entity object
- The GetObjectStateEntry() method takes an entity as an input and usage of this method is shown below. This method returns a single ObjectStateEntry object from the context and not the object instance. And also it will not look for the entity in the database, which means the database is not queried
The below code demonstrates how to use GetObjectStateEntry method to retrieve single entity.
Comparison between GetObjectByKey method with First operator
Even though both methods retrieve an object, the First() method will not check whether the requested entity is already exists in the context, simply query the database and returns the object as shown below. But using GetObjectByKey method, we can avoid extra round trip to the database because this method checks the context before executing query to the database.
The below code demonstrates how to use First() method to retrieve a single entity.
Using GetObjectByKey method for deleting entities
The following code demonstrates how to delete an entity.
In the above code, the DeleteObject() method marks the entity as deleted. In fact, the state of an entity in ObjectStateEntry object is marked as Deleted. When SaveChanges() method is invoked, the DELETE command is executed and the row is deleted from the database. That means, to use DeleteObject() method we need the entity to be deleted. If the entity is already retrieved and present in the context, it is fine. But sometimes you may want to delete data and knowing only the key value of the entity. In this situation GetObjectByKey method is used. The following code demonstrates this. The EntityKey class creates the EntityKey with the specified EntitySet, key property name and value of the key.
Compare the code block1 and this code block. We have already discussed that the GetObjectByKey() method returns object instance (in the code block 1). We have casted to a correct entity type to display or further operation. But in this case, we are just deleting it. So, we have not done any casting. In the above code, GetObjectByKey method looks for entity in context and retrieves the database and gets the object.
More Resources
- POCO class in Entity Framework
- POCO vs Entity Objects with comparison table
- Rules to be followed while creating POCOs - 4 important rules
- How to create a POCO class, integrate with ObjectContext, executing a query with POCOs
- How to load related POCO entities - loading patterns and their differences in their usage with examples
- How to perform Lazy Loading with POCO classes
- What is Change tracking in POCOs, ways of tracking
- Snapshot change tracking with DetectChanges() method
- Change tracking with proxies, How to create proxies?
- Instantiate POCO classes using ObjectContext.CreateObject method
- Using the DetectChanges() method to Fix-up Relationship in poco entities
- Entity Framework EntityKey object
- How to create an EntityKey in Entity Framework
- Loading Related entities in EF
- How to change the state of an entity using ChangeObjectState method of ObjectStateManager
- ChangeState method of ObjectStateEntry class
- Update an entity in a disconnected scenario using ApplyCurrentValues method
- Using ApplyOriginalValues method
- ObjectStateEntry class
- Entity state in Entity Framework - what, how, why?
- AcceptAllChanges and SaveChanges methods in Entity Framework
Azure Q & A
Azure Platform
Grid-View
GridView CommandField example
Details-View
GridView and DetailsView Master/Detail page using SqlDataSource control
POCO
POCO overview and advantages - POCO class, Entity Framework in Enterprise Applications
Entity Framework
Query entity data model using linq to entities
Array List
Difference between arraylist and list collection
Web Services
How to create a Web service using Visual Studio.net
Form-View
FormView DataBound Event
Object Oriented Programming
Calling base class constructor in C#
Linq
Convert a sequence to a generic list using ToList()method
Project Ideas
Project ideas for students
AccountingSoftware
Accounting Software
MVC
Creating an ASP.Net MVC 3 application
.Net
Using assemblies in .net applications
ASP .Net
How to implement form validation using ASP.Net 2.0 Validation Controls
VB .Net
Constructors in Visual Basic.Net