1

I wrote my code in ASP.NET MVC 4. I Create a Edit form using MVC edit template and this is my POST code to save edited data.

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

This code run correctly and there is no error. But when redirect to user profile occurred, modified fields are still have the previous value.
What should I do ?

Thanks in advance.

Mojtaba
  • 1,470
  • 4
  • 18
  • 25

2 Answers2

4

I would say it´s because the profile variable is not "connected" to the context. The context is not aware of the profile object. So when running context.SaveChanges() the changes in the profile variable goes unnoticed.

You need to update the update object with the values from profile. Or perhaps attach the profile object to the context.

Check this post on how to attach to the context prior saving Entity Framework 4 - AddObject vs Attach

Community
  • 1
  • 1
Tobias Nilsson
  • 512
  • 2
  • 13
  • Thanks, but I'm assign `profile` object to `update` object that connected to the context. This is not Enough ? – Mojtaba Jan 08 '13 at 11:36
  • 2
    @Mojtaba no this just points the update variable at a different object. It doesn't change the object that update originally points at. This is the one you need to change because it is the one EF knows about. – Rhumborl Jan 08 '13 at 11:37
  • Try to attach the profile object to the context as my link states. – Tobias Nilsson Jan 08 '13 at 11:39
3

It looks like you aren't actually changing the data in object returned from the database. You are setting update = profile, but this just dereferences the update variable so it no longer points at the object being tracked by EF.

You need to copy all the property values from profile to update.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45