Show / Hide Table of Contents

    DataContext.Rollback() Method

    .NET Standard 2.x

    Rolls back the current database transaction from a pending state.

    Namespace: SnapObjects.Data

    Assembly: SnapObjects.Data.dll

    Syntax

      public virtual void Rollback();
    

    Examples

    The following code example how to roll back the transaction.

    using Appeon.ApiDoc.Models.School;
    using SnapObjects.Data;
    using System;
    
    namespace Appeon.ApiDoc.DataContextExamples
    {
        public class RollbackExample
        {
            private readonly SchoolContext _context;
            public RollbackExample(SchoolContext context)
            {
                _context = context;
            }
    
            public void Example()
            {
                // Starts the transaction.
                _context.BeginTransaction();
    
                try
                {
                    string sql = @"INSERT Department
                        (DepartmentId, Name,Budget,StartDate, Administrator) 
                        VALUES (1, 'Engineering', 350000, '2007-09-01', 2)";
    
                    _context.SqlExecutor.Execute(sql);
    
                    // Attempts to commit the transaction.
                    _context.Commit();
                    Console.WriteLine("Record has been written to database.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                    Console.WriteLine("Message: {0}", ex.Message);
    
                    // Attempts to roll back the transaction.
                    try
                    {
                        _context.Rollback();
                    }
                    catch (Exception ex2)
                    {
                        // Handle any errors that may have occurred on the server that 
                        // could cause the rollback to fail. 
                        // Such as a closed connection.
                        Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                        Console.WriteLine("Message: {0}", ex2.Message);
                    }
                }
    
                /*This code produces the following output:
    
                Commit Exception Type: System.Data.SqlClient.SqlException
                Message: Violation of PRIMARY KEY constraint 'PK_Department'. 
                Cannot insert duplicate key in object 'dbo.Department'. 
                The duplicate key value is (1).
                The statement has been terminated.
                */
            }
        }
    }
    

    Applies to

    .NET Standard

    2.x

    Back to top Generated by Appeon