標籤: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.
- [HttpPost]
- /// <summary>
- /// 執行修改的代碼
- /// </summary>
- /// <param name="model"></param>
- /// <returns></returns>
- public ActionResult Modify(BlogArticle model)
- {
- try
- {
- //1.將實體物件 a.加入 EF 對象容器中,並 b.擷取 偽封裝類對象
- DbEntityEntry<BlogArticle> entry = db.Entry<BlogArticle>(model);
- //2.將封裝類對象的狀態設定為 unchanged
- entry.State = System.Data.EntityState.Unchanged;
- //3.設定 被改變的屬性
- entry.Property(a => a.ATitle).IsModified = true;
- entry.Property(a => a.AContent).IsModified = true;
- entry.Property(a => a.ACate).IsModified = true;
-
- //4.提交到資料庫 完成修改
- db.SaveChanges();
- //5.更新成功,則命令瀏覽器 重新導向 到 /Home/List 方法
- return RedirectToAction("Index", "Home");
- }
- catch (Exception ex)
- {
- return Content("修改失敗~~~" + ex.Message);
- }
- }
ASP.NET MVC + EF 更新的幾種方式