LINQ to SQL - Transaction

DLinq 对事务的支持非常灵活。缺省情况下,DataContext.SubmitChanges() 就会自动启动一个事务,确保所有操作在同一个事务下进行。
public class DataContext : IDisposable

{

    public virtual void SubmitChanges(ConflictMode failureMode)

    {

        // 省略部分代码...

        

        transaction = this.provider.Connection.BeginTransaction(IsolationLevel.ReadCommitted);

        this.provider.Transaction = transaction;

        

        new ChangeProcessor(this.services, this).SubmitChanges(failureMode);

        

        this.AcceptChanges();

        this.provider.ClearConnection();

        

        transaction.Commit();

        return;



        // 省略部分代码...

    }

}

我们还可以显示启用 DataContext 的事务。
using (DataClasses1DataContext context = new DataClasses1DataContext(connStr))

{

    context.Transaction = context.Connection.BeginTransaction();

    try

    {

        var user = new User { Name = "wangwu", Age = 14 };

        context.Users.Add(user);

        context.SubmitChanges();



        context.Transaction.Commit();

    }

    catch

    {

        context.Transaction.Rollback();

    }

}

同样,我们可以使用 System.Transactions.TransactionScope 创建跨 DataContext 的分布事务环境。
using (TransactionScope scope = new TransactionScope())

{

    try

    {

        using (DataClasses1DataContext context = new DataClasses1DataContext(connStr))

        {

            var user = new User { Name = "wangwu", Age = 14 };

            context.Users.Add(user);

            context.SubmitChanges();

        }



        using (DataClasses1DataContext context = new DataClasses1DataContext(connStr))

        {

            var user = new User { Name = "wangwu", Age = 14 };

            context.Users.Add(user);

            context.SubmitChanges();

        }



        scope.Complete();

    }

    catch

    {

    }

}

你可能感兴趣的:(transaction)