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.代码部分

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

 

posted on 2017-05-24 17:50  漫思  阅读(7836)  评论(0编辑  收藏  举报

导航