TransactionScope与DBContext - 最佳实践 [英] TransactionScope with DBContext - best practices

查看:134
本文介绍了TransactionScope与DBContext - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想知道有什么区别:



版本1:

Hi,

I was wondering is there any difference:

Version 1:

using (dbcontext = new DBContext())
{
   //read from context here
   //modify context here
   using (transactionscope = new TransactionScope())
   {
      dbcontext.SaveChanges();

      dbcontext.Database.ExecuteSQLCommand("UPDATE table...");
      transactionscope.Complete();
   }
}



版本2:


Version 2:

using (transactionscope = new TransactionScope())
{
   using (dbcontext = new DBContext())
   {
      //read from context here
      //modify context here
      dbcontext.SaveChanges();

      dbcontext.Database.ExecuteSQLCommand("UPDATE table...");
   }
   transactionscope.Complete();
}



谢谢


Thanks

推荐答案

首先,SaveChanges不需要单独的交易因为它默认包含在事务中。



更大的问题是你对上下文做的其他操作。例如,修改上下文意味着另一次调用SaveChanges。如果是这样,那么将SaveChanges调用包装在单个事务中确保保存全部或全部。



另一种情况是如果你使用两个上下文。将它们包装在单个事务中也是有意义的。
First thing is that the SaveChanges does not need a separate transaction since it's wrapped inside a transaction by default.

The bigger question is what other operations you do with the context. For example does the modify context mean another call to SaveChanges. If it does, then wrapping both SaveChanges calls inside a single transaction ensures that all or nothing is saved.

Another scenario would be if you use two contexts. Again it would make sense to wrap them inside a single transaction.


这篇关于TransactionScope与DBContext - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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