LINQ to SQL 中的 TransactionScope 与事务 [英] TransactionScope vs Transaction in LINQ to SQL

查看:32
本文介绍了LINQ to SQL 中的 TransactionScope 与事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LINQ to SQL 中的经典事务模式有什么区别,例如:

What are the differences between the classic transaction pattern in LINQ to SQL like:

using(var context = Domain.Instance.GetContext())
{
    try
    {
        context.Connection.Open();
        context.Transaction = context.Connection.BeginTransaction();
        /*code*/
        context.Transaction.Commit();
    }
    catch
    {
        context.Transaction.Rollback();
    }         
}

与 TransactionScope 对象对比

vs the TransactionScope object

using (var context = Domain.Instance.GetContext())
using (var scope = new TransactionScope())
{
    try
    {
        /*code*/
        scope.Complete();
    }
    catch
    {
    }
}

推荐答案

Linq2SQL 将使用隐式事务.如果您的所有更新都在一次提交中完成,您可能不需要自己处理事务.

Linq2SQL will use an implicit transaction. If all of your updates are done within a single Submit, you may not need to handle the transaction yourself.

来自文档(重点是我的):

From the documentation (emphasis mine):

当您调用 SubmitChanges 时,LINQ to SQL 会检查该调用是否在事务范围内,或者事务属性 (IDbTransaction) 是否设置为用户启动的本地事务.如果没有找到任何事务,LINQ to SQL 将启动一个本地事务 (IDbTransaction) 并使用它来执行生成的 SQL 命令. 当所有 SQL 命令都成功完成后,LINQ to SQL 提交本地事务并返回.

When you call SubmitChanges, LINQ to SQL checks to see whether the call is in the scope of a Transaction or if the Transaction property (IDbTransaction) is set to a user-started local transaction. If it finds neither transaction, LINQ to SQL starts a local transaction (IDbTransaction) and uses it to execute the generated SQL commands. When all SQL commands have been successfully completed, LINQ to SQL commits the local transaction and returns.

这篇关于LINQ to SQL 中的 TransactionScope 与事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆