Sitecore

Editcontext inside editcontext == Bad things.

As a developer, you need to be able to edit a Sitecore item for different reasons. We had a issue were we updated users data on login. The process was a bit complex and we needed to calculate multiple fields and values for each user and set it on their profileitem.

When editing a Sitecore item, the developer uses a editcontext:

using (new EditContext(item))
{
    item["FieldName"] = "Value";
}

However we had multiple fields needed to be edited, so we combined the field edits in one editcontext. At some point a nested method created a new editcontext with the same item.

using (new EditContext(item))
{
    // Update item
    CalculateFieldValueAndSet(item)
    // Update item
    item["Field1"] = "FieldValue";
}
private void CalculateFieldValueAndSet(Item item)
{
     // Calculate value
     var value = "a" + "b";
     using (new EditContext(item))
     {
          item["FieldName"] == value;
     {
}

When the editcontext inside CalculateFieldValueAndSet is closed, it closes all editing of the item resulting in a “Item is not en editing mode” error:

Exception: Sitecore.Exceptions.EditingNotAllowedException
Message: Item '/sitecore/content/user/B/bd/bd' is not in editing mode. Item ID: {0}
Source: Sitecore.Kernel

So be careful when using editcontext for complex and editing multiple fields on a item. 🙂

Advertisements

2 thoughts on “Editcontext inside editcontext == Bad things.

    1. I would recommend using “IsEditing” to check if the item is already in EditMode.
      Item.Editing.IsEditing

      If not in editing, you can start editing by using:

      Item.Editing.BeginEdit();
      And close it again with
      Item.Editing.EndEdit();

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s