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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read