, , ,

How to update data in Kentico using transaction method

Posted by

To update data in Kentico using the transaction method, you can follow these steps:

  1. Import the necessary Kentico namespaces in your code-behind file:
using CMS;
using CMS.DataEngine;
  1. Write your update code within a transaction scope:
using (var scope = new CMSTransactionScope())
        // Perform your update operations here

        // Example: Update a document field
        int documentID = 123;
        string newTitle = "Updated Title";

        DocumentHelper.RunInTransaction(() =>
            // Retrieve the document using its ID
            var doc = DocumentHelper.GetDocument(documentID, null);

            if (doc != null)
                // Update the document field
                doc.SetValue("DocumentName", newTitle);
                DocumentHelper.UpdateDocument(doc, null, false);

        // Commit the transaction

        // Optionally, perform additional actions upon successful update
    catch (Exception ex)
        // Handle the exception or log any error messages

        // Rollback the transaction

In this example, the code is wrapped within a CMSTransactionScope to ensure that all the update operations are performed within a single transaction. This helps maintain data integrity and allows you to rollback the changes if an exception occurs.

Inside the transaction scope, you can perform your update operations. In the provided example, a document field is updated using the DocumentHelper. The RunInTransaction method ensures that the update is performed within the transaction context.

After performing the necessary updates, the transaction is committed using scope.Commit(). If any exception occurs, the transaction is rolled back using scope.Rollback().

It’s important to note that the transaction method should be used when updating multiple objects or performing complex operations that require atomicity (all or nothing) and data consistency. For simple updates, you can use the built-in Kentico API methods without explicitly managing a transaction.

Make sure to adjust the code according to your specific update requirements, such as updating different types of objects (e.g., documents, custom tables) or modifying multiple fields.

Remember to handle exceptions appropriately, log any errors, and provide user feedback or error messages as needed.