Entity Framework使用事务示例

//using System.Transactions;
try
{
    using (testContext context = new testContext())
    {
        using (TransactionScope trans = new TransactionScope())
        {
            //1.扣款
            Account account = context.Accounts.Where(a => a.Id == 1).FirstOrDefault();
            account.Money -= 100;
            context.SaveChanges();

            //throw new Exception("error");

            //2.提现
            Withdraw withdraw = new Withdraw()
            {
                Aid = account.Id,
                Money = 100
            };
            context.Withdraws.Add(withdraw);
            context.SaveChanges();

            //3.提交                    
            trans.Complete();
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}


评论: 0 | 引用: 0 | 查看次数: 4489
发表评论
登录后再发表评论!