[EF]共享事務處理連接

不同的context對象可以通過共享連接將數據的更新操作合併在相同的事務處理範圍中,參考以下的設置:

 KTStoreContext context_s = new KTStoreContext(context.Database.Connection
                            , contextOwnsConnection: false);

爲了共享事務處理,因此調用另外一個版本的構造函數創建所需的context對象:除此之外,還要指定使用此連接的事務處理環境。

context_s.Database.UseTransaction(transaction.UnderlyingTransaction);

完成以上的設置。context與context_s就會同時被限制在一個事務處理範圍中。

 using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var products = context.Products;
                        foreach (Product product in products)
                        {
                            int p = (int)(product.Price * 0.5);
                            product.SPrice = p;
                        }
                        int c = context.SaveChanges();

                        KTStoreContext context_s = new KTStoreContext(context.Database.Connection
                            , contextOwnsConnection: false);
                        context_s.Database.UseTransaction(transaction.UnderlyingTransaction);
                        context_s.Database.ExecuteSqlCommand("UPDATE Product SET SPrice =0 WHERE Id=10 ");
                     
                        transaction.Commit();
                        Console.WriteLine("更新了 {0} 項數據", c);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Console.WriteLine("事務處理失敗");
                    }
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章