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

    原文链接

  • 相关阅读:
    105.UDP通信实现广播
    104.tcp多线程读写实现群聊
    103.tcp通信实现远程控制
    102.tcp实现多线程连接与群聊
    101.自动注入
    100.dll调用
    99.遍历进程并直接写入内存
    98.TCP通信传输文件
    97.TCP通信
    96.udp通信
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/9801543.html
Copyright © 2011-2022 走看看