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.

if (reviewInstance == null)
{
using (WIN_DataEntities data = new WIN_DataEntities())
      {
      	data.Review.MergeOption = 
System.Data.Objects.MergeOption.NoTracking;

            var q = from r in data.Review
                    where r.in_Id == this.ReviewId
                    select r;

            reviewInstance = q.FirstOrDefault();

            reviewInstance.OrganizationReference.Load(
System.Data.Objects.MergeOption.NoTracking);                    
}
}

return reviewInstance;

Detached Entities in the The Entity Framework

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.

if (reviewInstance == null)
{
using (WIN_DataEntities data = new WIN_DataEntities())
      {
		// Run the query
            var q = from r in data.Review
                    where r.in_Id == this.ReviewId
                    select r;

		// Get the first record
            reviewInstance = q.FirstOrDefault();

// Detach the instance
		data.Detach(reviewInstance);
}
}

return reviewInstance;

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.

using (WIN_DataEntities data = new WIN_DataEntities())
{
// Attach the previously detached object
	data.Attach(reviewInstance);
}

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.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds