[C#] EntityFramework交易写法Sample Code

EntityFramework transaction Sample Code

第一种写法,只需一个db.SaveChanges()即可。

            NorthwindEntities db = new NorthwindEntities();


            try
           {
            Product p1 = db.Products.FirstOrDefault(m => m.ProductID == 1);
            p1.UnitPrice -= 1;//修改資料

            //假裝這裡意外發生
            throw new Exception("Crash");


            Product p2 = db.Products.FirstOrDefault(m => m.ProductID == 2);
            p2.UnitPrice += 1;//修改資料


            db.SaveChanges(); //都成功才SaveChanges()

            }catch(Exception ex)
            {

            }

第二种写法,之前已呼叫过db.SaveChanges(),想Rollback复原资料

须事先加入System.Transactions的参考

 NorthwindEntities db = new NorthwindEntities();

            //想要交易的範圍
            using (System.Transactions.TransactionScope scope=new System.Transactions.TransactionScope())
            {
                try
                {
                    Product p1 = db.Products.FirstOrDefault(m => m.ProductID == 1);
                    p1.UnitPrice -= 1;//修改資料
                    db.SaveChanges();//提交變更

                    //假裝意外發生,但之前已執行 db.SaveChanges();
                    throw new Exception("Crash");

                    Product p2 = db.Products.FirstOrDefault(m => m.ProductID == 2);
                    p2.UnitPrice += 1;//修改資料
                    db.SaveChanges();
                    scope.Complete();//都成功
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                } 
            }//end using 

上述TransactionScope建构式预设值↓ (最严格等级,只要其中一笔交易失败,就整个失败,其它连线要读取异动资料,都必须等待此交易完成)

  NorthwindEntities db = new NorthwindEntities();


            //想要交易的範圍
            using(TransactionScope scope=new  TransactionScope( TransactionScopeOption.Required,
                                                      new TransactionOptions() { IsolationLevel=IsolationLevel.Serializable})) 
            {
                try
                {
                    Product p1 = db.Products.FirstOrDefault(m => m.ProductID == 1);
                    p1.UnitPrice -= 1;//修改資料
                    db.SaveChanges();//提交變更

                    //假裝意外發生,但之前已執行 db.SaveChanges();
                    throw new Exception("Crash");

                    Product p2 = db.Products.FirstOrDefault(m => m.ProductID == 2);
                    p2.UnitPrice += 1;//修改資料
                    db.SaveChanges();
                    scope.Complete();//都成功
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                } 
            }//end using 

※第二种写法也支援在TransactionScope区块里透过ADO.net异动资料库

猜你喜欢

转载自blog.csdn.net/wwwdsbjdqcom/article/details/81053012
今日推荐