木子屋 Dnawo's BLOG

Entity Framework使用事务示例

👤 dnawo 📅 2013-01-17 👁 5430 👍 0 💬 0 🔄 本站原创
//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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ASP.NET MVC3中Html.ActionLink使用示例 下一篇 → ASP.NET MVC3获取GET和POST参数示例