[C.C++] C#在Entity Framework中实现事务回滚

3323 8
黑夜隐士 2022-11-10 10:04:24 | 显示全部楼层 |阅读模式
在使用Entity Framework为主从表添加数据,当一个表添加数据成功,另一个表添加数据失败,这时候就需要用到事务回滚。
比如有以下关系的2张表。


客户端使用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表数据的时候,模拟了一个异常,通过断点调试执行完毕,发现数据库中没有增加任何数据。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对中国红客联盟的支持。如果你想了解更多相关内容请查看下面相关链接

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行