Skip to content

Transactions

Mike Hanson edited this page Mar 5, 2018 · 3 revisions

SqlRepo uses SqlConnection under the hood to execute SQL commands. This allows us to use TransactionScope from the System.Transactions namespace in order to utilize transactions.

The following code wraps both insert commands inside the transaction, if there is an exception when inserting the Customer Address the transaction will roll back and the Customer is not inserted.

using (var transaction = new TransactionScope())
{
    var customer = this.repositoryFactory.Create<Customer>()
        .Insert()
        .With(e => e.Name, "CustomerName")
        .Go(); 

    var customerAddress = this.repositoryFactory.Create<CustomerAddress>()
        .Insert()
        .With(e => e.CustomerId, customer.Id)
        .With(e => e.Postcode, "ABC-123")
        .Go()

    transaction.Complete();
}