zoukankan      html  css  js  c++  java
  • Entity Framework

    LINK

    With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

    Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful.

    The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

    I.e. something like this (bad):

    using (TransactionScope scope = new TransactionScope())
    {
        //Do something with context1
        //Do something with context2
    
        //Save and discard changes
        context1.SaveChanges();
    
        //Save and discard changes
        context2.SaveChanges();
    
        //if we get here things are looking good.
        scope.Complete();
    }

    If context1.SaveChanges() succeeds but context2.SaveChanges() fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1, so you can't replay or effectively log the failure.

    But if you change your code to look like this:

    using (TransactionScope scope = new TransactionScope())
    {
        //Do something with context1
        //Do something with context2
    
        //Save Changes but don't discard yet
        context1.SaveChanges(false);
    
        //Save Changes but don't discard yet
        context2.SaveChanges(false);
    
        //if we get here things are looking good.
        scope.Complete();
        context1.AcceptAllChanges();
        context2.AcceptAllChanges();
    
    }

    While the call to SaveChanges(false) sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager if you want.

    This means if the transaction actually aborts you can compensate, by either re-trying or logging state of each contexts ObjectStateManager somewhere.

    See my blog post for more.

  • 相关阅读:
    js把秒数转换为HH:MM:SS及时分秒格式
    java将流量KB转换为GB、MB、KB格式
    java将秒数转换为时分秒格式
    springboot前端向后端请求返回html语句
    java判断手机号三大运营商归属的工具类
    Java读取txt文件、excel文件的方法
    Linux安装JDK、Mysql和Tomcat
    原理篇—文件包含漏洞
    原理篇—上传漏洞
    原理篇—CSRF 跨站脚本请求伪造
  • 原文地址:https://www.cnblogs.com/dufu/p/3961880.html
Copyright © 2011-2022 走看看