zoukankan      html  css  js  c++  java
  • Entity Framework中DbContext结合TransactionScope提交事务的正确方式

    问:


    I would like know what is the best possible way to implement transactions with DBContext. In particular,

    1. Does DbContext.SaveChanges implement transaction internall if i change multiple entities?
    2. If i want to call DbContext.SaveChanges multiple times(same contxet/different contxets), how transaction can be achieved?

    答:


    1. Yes. SaveChanges uses transaction internally.(也就是说SaveChanges方法默认会在内部自己开启一个事务,所有用SaveChanges方法提交到数据库的SQL语句都在同一个数据库事务中)
    2. Use TransactionScope to wrap multiple calls to SaveChanges

    Example:

    using(var scope = new TransactionScope(TransactionScopeOption.Required,
        new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
    {
        // Do something 
        context.SaveChanges();
        // Do something else
        context.SaveChanges();
    
        scope.Complete();
    }

    从上面的代码我们可以看出来在Entity Framework中,DbContext(即上面的context变量)上所有实体数据的更改都会在DbContext.SaveChanges方法被调用时提交到数据库,也就是DbContext.SaveChanges方法被调用时,内部会打开一个数据库连接来在数据库上执行相关的SQL语句,然后关闭该数据库连接。由于上面代码中两次DbContext.SaveChanges方法的调用都在一个TransactionScope的using代码块内,所以这两次SaveChanges方法调用开启的数据库连接都在同一个数据库事务下,保证了两次SaveChanges方法执行的SQL语句都在同一个数据库事务下被提交。

    原文链接

  • 相关阅读:
    数据结构
    查找算法
    排序算法
    ThreadPoolExecutor
    Python map()函数
    Python惰性序列
    Python iterator迭代器
    Python yield关键字 和 Generator(生成器)
    Python 列表生成式(List Comprehensions)
    Python 迭代(iteration)
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/9801543.html
Copyright © 2011-2022 走看看