DataContext.UseTransaction(DbTransaction transaction) Method
.NET Standard 2.x
Uses a transaction as the current database transaction.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public virtual IAdoDbTransaction UseTransaction(DbTransaction transaction);
Parameters
transaction
System.Data.Common.DbTransaction
A DbTransaction
object which will be used as the current database transaction.
Returns
IAdoDbTransaction
SnapObjects.Data.IAdoDbTransaction
Returns the new database transaction if succeeds; returns null
If the transaction
argument is null
.
Examples
The following code example uses an existing DbTransaction
object as the current transaction.
using System;
using System.Data.Common;
namespace Appeon.ApiDoc.DataContextExamples
{
public class UseTransactionExample
{
private readonly SchoolContext _context;
public UseTransactionExample(SchoolContext context)
{
_context = context;
}
public void Example(DbTransaction trans)
{
// Uses trans as the current transaction
_context.UseTransaction(trans);
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