ASP.NET MVC 简单事务
//实例化查询上下文 using ( BookStoreEntities db = new BookStoreEntities()) { //找到需要价格和名称的数据实体对象 var book = db.Books.FirstOrDefault(x => x.Title == "ASP.NET NVC 程序开发"); if(book!=null) { //更改属性值 book.Title = "ASP.NET NVC 程序开发"; book.Price = 30; //保存更改,只有调用了SaveChannges()方法后,更新后的数据才能被写入数据库 db.SaveChanges(); } } #region 使用事务新增 using (BookStoreEntities db = new BookStoreEntities()) { //声明事务对象 System.Data.Common.DbTransaction tran = null; //手动打开链接并创建事务 db.Conection.Open(); tran = db.Connection.BeginTransaction(); try { var book = db.Books.FirstOrDefault(x => x.Title == "JavaScript语言与AJAX应用"); var order = new Orders() { Num = 1, Books = book, Address = "" }; db.AddToOrders(order); db.SaveChanges(); order.Address = "中国湖北武汉"; db.SaveChanges(); //提交事务 tran.Commit(); } //如果出现任何异常事务回滚 catch (Exception) { tran.Rollback(); } finally { //关闭连接 if (db != null && db.Connection.State != System.Data.ConnectionState.Closed) { db.Connection.Close(); } } #endregion