[EF]使用TransactionScope

在TransactionScope的范围中,不需要明确调用UserTransaction,即可将所有事务处理纳入相同的范围中,这适合更广泛的事务处理操作。

using System.Transactions;

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (KTStoreContext context = new KTStoreContext())
                {
                    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.ExecuteSqlCommand(
                            "UPDATE Product SET SPrice =0 WHERE Id=10 ");
                        
                        scope.Complete();
                        Console.WriteLine("更新了 {0} 项数据", c);
                    }
                    catch (Exception e) {
                        Console.WriteLine("事务处理失败");
                    }
                    Console.ReadKey();
                }
            }
发布了921 篇原创文章 · 获赞 379 · 访问量 326万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览