Show / Hide Table of Contents

    DataContext.BeginTransaction() Method

    .NET Standard 2.x

    Starts a database transaction, using the isolation level specified by the ContextOptions.

    Namespace: SnapObjects.Data

    Assembly: SnapObjects.Data.dll

    Syntax

      public virtual IAdoDbTransaction BeginTransaction();
    

    Returns

    SnapObjects.Data.IAdoDbTransaction

    Returns an IAdoDbTransaction object representing the new transaction.

    Examples

    The following code example starts a transaction using the isolation level specified by the ContextOptions.

    using System;
    using System.Data;
    
    namespace Appeon.ApiDoc.DataContextExamples
    {
        public class BeginTransactionExample
        {
            private readonly SchoolContext _context;
            public BeginTransactionExample(SchoolContext context)
            {
                _context = context;
            }
    
            public void Example1()
            {
                // Starts the transaction using the isolation level specified 
                // by the `ContextOptions`.
                _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);
                    }
                }
            }
        }
    }
    

    Applies to

    .NET Standard

    2.x

    Back to top Generated by Appeon