Working with Object Context in the Entity Framework

Entity Context in the Entity Framework

Welcome to this installment of the .NET Nuts & Bolts column where we'll delve deeper in to the Entity Framework. The focus will be on the entity context and some of the various things available such as detaching entities and attaching them again.

MergeOption.NoTracking

When queries are executed within an object context the items returned are automatically attached to the context. This means queries executed within the context increases the memory requirements as changes to those objects are tracked. The exception to this is when the query is executed with the MergeOption.NoTracking parameter. When the MergeOption.NoTracking is used the objects are not attached to the object context because changes won't be tracked. This can be beneficial when executing select only queries where you do not intend to update any of the query results. It is also especially useful when you have a particular entity to retrieve from the database and need to use it over and over during a process, but will not be updating it. The following code snippet demonstrates the retrieving of a particular entity from the database and using the MergeOption.NoTracking to ensure that it and the entities relationships are not added to the context and are therefore available to be passed as input to a number of methods during a long running process.

The MergeOption.NoTracking offers performance gains when used, but it isn't applicable when you are intending to make changes to the entities. The Entity Framework offers the capability to let you detach objects from an object context to allow for the associated resources to be reclaimed by the Entity Framework. In order to detach objects you call the Detach method and pass a reference to the object being detached. There are some items to understand about the detach process:

If the object being detached has related objects the related entities will not be detached. It only impacts the specific object passed and not their related entities. This is very important to remember as I've seen it trip up folks a number of times.

Relationship information is not maintained for a detached object.

State such as tracked changes and temporary keys are not maintained and thus does not affect data in the data source.

Cascading deletes and other referential constraints are not enforced on detached objects.

The following code snippet offers an alternate to the prior example that detaches the entity from the context. Note the difference where the OrganizationReference is not detached as well.

Attaching Entities

When a query is executed inside an object context in the Entity Framework the involved entities are automatically attached to the object context. It is also possible to attach objects to the context that weren't part of the current context. This can be used to attach objects that were previously detached. There are some items to understand about the attach process:

To attach an object it must be implemented with IEntityWithKey and have a valid key.

Objects are attached to the object context in an Unchanged state.

If the object being attached has updated property values, then use ApplyPropertyChanges to apply the updates.

The following code snippet shows code that would attach the Review entity that was previously detached.

In the example above the reviewInstance is attached in an unchanged state. The following code snippet demonstrates how to handle changes. It requires the original object to be available along with a second that contains the changes.

using (WIN_DataEntities data = new WIN_DataEntities())
{
// Attach the previously detached object in Unchanged state
data.Attach(reviewInstance);
// Apply changes to the original through a revised instance
data.ApplyPropertyChanges("Review", changedInstance);
// Save the changes
data.SaveChanges();
}

Summary

We have further explored the Entity Framework and seen how we can optimize memory usage through the MergeOption.NoTracking parameter for read-only queries. We also explored how to detach entities from the object context and attach them again, including the ability to apply changes that were made while detached.

Future Columns

The topic of the next column is yet to be determined. If you have something else in particular that you would like to see explained here you could reach me at mark.strawmyer@crowehorwath.com.

About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Comments

Excelent

Posted by Mauricio SÃ¡nchez
on 11/04/2012 10:21am

I am beginner in entity framework and this article helps me a lot, very good.

Top White Papers and Webcasts

When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.