Ejemplo n.º 1
0
        public static void ExampleE()
        {
            int     outputId = 1, inputId = 1;
            decimal transferAmount = 2000m;

            using (var scope = new TransactionScope())
            {
                Context.Contextb db1 = new Context.Contextb();
                Context.Contextb db2 = new Context.Contextb();

                //1 检索事务中涉及的账户
                var outputAccount = db1.OutputAccounts.Find(outputId);
                var inputAccount  = db2.InputAccounts.Find(inputId);

                //2 从输出账户上扣除1000
                outputAccount.Balance -= transferAmount;
                //3 从输入账户上增加1000
                inputAccount.Balance += transferAmount;

                //4 提交事务
                db1.SaveChanges();
                db2.SaveChanges();

                scope.Complete();
            }
        }
Ejemplo n.º 2
0
        public static void ExampleF()
        {
            int     outputId = 1, inputId = 1;
            decimal transferAmount = 10m;

            using (var db = new Context.Contextb())
            {
                using (var trans = db.Database.BeginTransaction())
                {
                    try
                    {
                        var sql = @"Update OutputAccounts set Balance=Balance-@amountToDebit where id=@outputId";
                        db.Database.ExecuteSqlCommand(sql, new SqlParameter("@amountToDebit", transferAmount), new SqlParameter("@outputId", outputId));

                        var inputAccount = db.InputAccounts.Find(inputId);
                        inputAccount.Balance += transferAmount;
                        db.SaveChanges();

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public static void ExampleD()
        {
            int     outputId = 1, inputId = 1;
            decimal transferAmount = 1000m;

            using (var db = new Context.Contextb())
            {
                //1 检索事务中涉及的账户
                var outputAccount = db.OutputAccounts.Find(outputId);
                var inputAccount  = db.InputAccounts.Find(inputId);
                //2 从输出账户上扣除1000
                outputAccount.Balance -= transferAmount;
                //3 从输入账户上增加1000
                inputAccount.Balance += transferAmount;

                //4 提交事务
                db.SaveChanges();
            }
        }