实体框架更新不工作
本文关键字:工作 更新 框架 实体 | 更新日期: 2023-09-27 17:50:56
我用ASP编写代码。Net MVC 4。我使用MVC编辑模板创建一个编辑表单,这是我的POST
代码来保存编辑过的数据。
[AcceptVerbs(HttpVerbs.Post)] [Authorize(Roles = "User")] public ActionResult Register(Models.UserBasicProfile profile) { if (ModelState.IsValid) { using (Models.SocialServicesDataContainer context = new Models.SocialServicesDataContainer()) { Models.UserBasicProfile update = context.UserBasicProfiles .SingleOrDefault(c => c.Id == profile.Id); if (update.Id > 0) { profile.RegisterDate = update.RegisterDate; update = profile; context.SaveChanges(); return RedirectToRoute("User_ShowProfile_Alter", new {username = User.Identity.Name }); } else { return View(profile); } } }
此代码运行正确,没有错误。但是当重定向到用户配置文件时,修改后的字段仍然具有以前的值。
我该怎么办?
我会说这是因为profile
变量没有"连接"到上下文。上下文不知道概要文件对象。因此,当运行context.SaveChanges()
时,配置文件变量的变化不会被注意到。
需要更新update object with the values from profile
。或者将概要文件对象附加到上下文。
查看这篇关于如何在保存实体框架4之前附加到上下文的文章- AddObject vs attach
看起来您实际上并没有更改从数据库返回的对象中的数据。您正在设置update = profile,但这只是取消了update变量的引用,因此它不再指向EF正在跟踪的对象。
您需要从配置文件中复制所有属性值来更新。