Thursday, February 7, 2013

Azure Lessons Learned (Part II)

I have a goal of posting things I have learned while developing an Azure solution (www.scuddle.com). The latest issue was this exception:

The context is already tracking a different entity with the same resource Uri

The resolution is pretty straight-forward – detach from the entity! I’ll explain…

I am using a custom Azure table storage provider, as many do, that provides functionality to Insert, Delete, Update, and Query tables for stored entities. Throughout the application (in this case, ASP.NET MVC 4), a new instance is created, entities are retrieved and updated, and then the instance is released.

However, if you perform an Update, you will have attached to a table entity, like this:

public void Update(TElement entity)
{
    this._tableServiceContext.AttachTo(this._tableName, entity, "*");
    this._tableServiceContext.UpdateObject(entity);
    this._tableServiceContext.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);
}

After the update, if you attempt to query the table for that same entity, you might get the “context is already tracking” exception, because you have attached to the entity in question, but only if you are using the same instance of your storage provider.

The solution is to detach. In the code below, I am detaching both before the update, which does not throw an exception, and also after the update. By doing so, queries immediately following the update are successful.

public void Update(TElement entity)
{
    this._tableServiceContext.Detach(entity);
    this._tableServiceContext.AttachTo(this._tableName, entity, "*");
    this._tableServiceContext.UpdateObject(entity);
    this._tableServiceContext.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);
    this._tableServiceContext.Detach(entity);
}

No comments:

Post a Comment