• 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语句都在同一个数据库事务下被提交。

    原文链接

  • 相关阅读:
    Linux 系统下10个查看网络与监听的命令
    Linux下用gdb 调试、查看代码堆栈
    GPIO引脚速度的应用匹配
    编写安全的代码——小心有符号数的右移操作
    C语言实现类似C++的容器vector
    求字符串长度之递归与非递归的C语言实现
    字符串拷贝函数递归与非递归的C语言实现
    WriteLogHelper
    JsonHelper
    ConfigHelper
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/9801543.html
Copyright © 2020-2023  润新知