public void TransactionsTest()
        {
            using (var context = new testContext())
            {
                //使用EF事务  在vs2013中先升级Entity Framework框架至6.x
                //工具 - Nuget程序包管理器 -管理解决方案的Nuget程序包 - 更新
                using (var dbContextTransaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        int i = context.Database.ExecuteSqlCommand(
                             @"UPDATE Category SET Name = Name + '_扩展' WHERE Name LIKE '%手机%'"
                             );
                        var query = context.Products.Where(p => p.ParentID == 2);
                        foreach (var post in query)
                        {
                            post.Name += "_extaa";
                        }
                        context.SaveChanges();
                        dbContextTransaction.Commit(); //提交事务
                    }
                    catch (Exception)
                    {
                        dbContextTransaction.Rollback(); //回滚事务
                    }
                }
            }
        } 


本文转载:CSDN博客