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();