ef中使用事务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace 事务
{
    class Program
    {
        static void Main(string[] args)
        {
            MVC5Entities db = new MVC5Entities();


            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    db.Actions.Add(new Action { ActionName = "aaa", AreaName = "aaa", ControllerName = "aaa", FatherID = 0 });
                    db.SaveChanges();
                    int a = 0;
                    int b = 10 / a;
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);                    
                }
            }

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    db.Actions.Add(new Action { ActionName = "bbb", AreaName = "bbb", ControllerName = "bbb", FatherID = 0 });
                    db.SaveChanges();
                    int a = 0;
                    int b = 10 / a;
                    scope.Complete();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }


            Console.WriteLine("ok");
        }
    }
}
原文地址:https://www.cnblogs.com/tgdjw/p/4718618.html