Entity Framework实现事务回滚

在使用Entity Framework为主从表添加数据,当一个表添加数据成功,另一个表添加数据失败,这时候就需要用到事务回滚。

 

比如有以下关系的2张表。

1

 

客户端使用TransactionScope类可以实现事务回滚。

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    using (CountryDetailsEntities db = new CountryDetailsEntities())
                    {
                        Country country = new Country();
                        country.CountryName = "USA";
                        db.Countries.Add(country);
                        db.SaveChanges();
                        if (country.CountryID > 0)
                        {
                            int a = 0;
                            int total = 10 / a;
                            State state = new State();
                            state.CountryID = country.CountryID;
                            state.StateName = "NewYork";
                            db.States.Add(state);
                            db.SaveChanges();
                        }
                    }
                    ts.Complete();
                }
                
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

以上,在添加State表数据的时候,模拟了一个异常,通过断点调试执行完毕,发现数据库中没有增加任何数据。   

原文地址:https://www.cnblogs.com/darrenji/p/3965233.html