Search code examples
c#sqllinqtransactionscope

linq to sql transaction


I have the following code below with different calls to stored procedures.

My problem is that I want this to be in a transaction, so if one of the DB methods fails then it will automatically rollback the pending changes.

I have read some articles on Stackoverflow/Microsoft pages which states that the SubmitChanges will wrap these in transactions for me.

The problem is that the spClearTablesForReplication method clears the tables and later on the code fails on purpose (for testing) and then all my tables are empty (is not rolled back)

XalSqlDataContext db = new XalSqlDataContext();
db.spClearTablesForReplication();
db.spUpdateStockItemGroup(ConvertToXElement(typeof(List<StockItemGroup>),    stockItemGroups));
db.spUpdateStockItemSubGroup(ConvertToXElement(typeof(List<StockItemSubGroup>),    stockItemSubGroups));

db.SubmitChanges();

Any clues/solutions for this.


Solution

  • Wrap your code in a TransactionScope using block and then that will rollback unless it reaches the point where you call transactionScope.Complete().

    Example:

    using (TransactionScope transactionScope = new TransactionScope())
    {
        //code here
        transactionScope.Complete();
    }