DataContext.BeginTransactionAsync() Method
.NET Standard 2.x
Asynchronously starts a database transaction, using the isolation level specified by the ContextOptions
.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public virtual Task<IAdoDbTransaction> BeginTransactionAsync()
Returns
Task<IAdoDbTransaction>
Returns a task that represents the asynchronous operation.
Examples
The following code example starts an asynchronous transaction using the isolation level specified by the ContextOptions
.
using System;
using System.Data;
using System.Threading;
namespace Appeon.ApiDoc.DataContextExamples
{
public class BeginTransactionAsyncExample
{
private readonly SchoolContext _context;
public BeginTransactionAsyncExample(SchoolContext context)
{
_context = context;
}
public async void Example1()
{
// Starts the asynchronous transaction using the isolation level specified
// by the `ContextOptions`.
await _context.BeginTransactionAsync();
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 asynchronously.
try
{
await _context.RollbackAsync();
}
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