ASP.NET MVC 簡單事務添加
阿新 • • 發佈:2019-01-20
javascrip mon 添加 找到 .com 事務 clas 保存 null
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
ASP.NET MVC 簡單事務添加