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

來源:互聯網
上載者:User

標籤:index   art   redirect   first   uber   res   article   returns   升級版   

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);              }          }   升級版:db.Entry(model).State = EntityState.Unchanged;db.Entry(model).Property(m => m.欄位名).IsModified = true;db.SaveChanges();  

 

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.