ASP.NET MVC + EF 更新的几种方式

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.         }   
  30. 升级版:
  31. db.Entry(model).State = EntityState.Unchanged;
    db.Entry(model).Property(m => m.字段名).IsModified = true;
    db.SaveChanges();  

posted @ 2014-10-29 17:37  -Ward-  阅读(360)  评论(0编辑  收藏  举报