的TransactionScope与交易中的LINQ to SQL [英] TransactionScope vs Transaction in LINQ to SQL

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

问题描述

什么是到SQL像LINQ的经典交易模式之间的差异:

 使用(VAR上下文= Domain.Instance.GetContext())
{
    尝试
    {
        context.Connection.Open();
        context.Transaction = context.Connection.BeginTransaction();
        / * code * /
        context.Transaction.Commit();
    }
    抓住
    {
        context.Transaction.Rollback();
    }
}

相较于TransactionScope的对象

 使用(VAR上下文= Domain.Instance.GetContext())
使用(VAR范围=新的TransactionScope())
{
    尝试
    {
        / * code * /
        scope.Complete();
    }
    抓住
    {
    }
}


解决方案

LINQ2SQL将使用隐式事务。如果你所有的更新都在一个单一的完成提交,你可能不需要自己处理事务。

从文档(重点煤矿):


  

当你调用的SubmitChanges,LINQ to SQL的检查,看看呼叫是否在交易范围,或者如果事务属性(IDbTransaction)设置为用户启动本地事务。 如果它发现没有交易,LINQ到SQL启动一个本地事务(IDbTransaction),并用它来执行生成的SQL命令。:当所有的SQL命令已顺利完成,LINQ到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();
    }         
}

vs the TransactionScope object

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

解决方案

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):

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.

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

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