ASP.NET MVC + EF 更新的几种方式(超赞)
2024-08-24 06:17:50
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();
最新文章
- C# Byte[] 转String 无损转换
- __index
- strace追踪未开始或者来不及捕获pid的进程(译)
- rdesktop共享剪贴板的问题
- 编译c
- python 延迟绑定
- 【C#】添加引用方式抛出和捕获干净的WebService异常
- C#的图像处理方法--(作者:http://conner-wang.spaces.live.com转载)
- 0429 Scrum团队成立与第6-7章读后感
- Android学习笔记----解决“com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536”问题
- 不要让mysql犹豫不决
- URI、URL和URN
- BZOJ1821: [JSOI2010]Group 部落划分
- SVN的版本日期
- Shredding Company(dfs)
- xml动态修改 dom4j修改
- 动态添加试题选项按钮 radioButton(一)
- React + Node 单页应用「一」前端搭建
- mybatis是如何防止SQL注入的
- Spring boot多模块(moudle)中的一个注入错误(Unable to start embedded container; nested exception is org)