ASP.NET MVC + EF 更新的幾種方式

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   for   sp   

1.常用

db.Entry(實體).State = EntityState.Modified;
db.SaveChanges();

2.指定更新

db.Configuration.ValidateOnSaveEnabled = false;
db.TUser.Attach(實體);
ObjectStateEntry stateEntry = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.GetObjectStateEntry(實體);
stateEntry.SetModifiedProperty("欄位1");
stateEntry.SetModifiedProperty("欄位2");
db.SaveChanges();
db.Configuration.ValidateOnSaveEnabled = true;

3.指定更新(推薦!好用!)

TConsultant model = db.TConsultant.FirstOrDefault(t => t.ID == iID);
if (TryUpdateModel(model, new string[] { "Name", "Sex", "PhoneNuber", "CertificateNumber", "Email", "QQ", "Culture" }))
{
          db.SaveChanges();
          return Content("修改成功!");
}

4.

  1. [HttpPost]  
  2.         /// <summary>  
  3.         /// 執行修改的代碼  
  4.         /// </summary>  
  5.         /// <param name="model"></param>  
  6.         /// <returns></returns>  
  7.         public ActionResult Modify(BlogArticle model)  
  8.         {  
  9.             try  
  10.             {  
  11.                 //1.將實體物件 a.加入 EF 對象容器中,並 b.擷取 偽封裝類對象  
  12.                 DbEntityEntry<BlogArticle> entry = db.Entry<BlogArticle>(model);  
  13.                 //2.將封裝類對象的狀態設定為 unchanged  
  14.                 entry.State = System.Data.EntityState.Unchanged;  
  15.                 //3.設定 被改變的屬性  
  16.                 entry.Property(a => a.ATitle).IsModified = true;  
  17.                 entry.Property(a => a.AContent).IsModified = true;  
  18.                 entry.Property(a => a.ACate).IsModified = true;  
  19.   
  20.                 //4.提交到資料庫 完成修改  
  21.                 db.SaveChanges();  
  22.                 //5.更新成功,則命令瀏覽器 重新導向 到 /Home/List 方法  
  23.                 return RedirectToAction("Index", "Home");  
  24.             }  
  25.             catch (Exception ex)  
  26.             {  
  27.                 return Content("修改失敗~~~" + ex.Message);  
  28.             }  
  29.         }   

ASP.NET MVC + EF 更新的幾種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.