1
votes

I want to make it possible for user to change his profile details(except UserId,Username and password(password changed in another view))

so in my method when I make it like that

    public void SaveUser(UserProfile user)
    {
        context.Entry(user).State = System.Data.EntityState.Modified;
        context.SaveChanges();
    }

I get an error Store update, insert, or delete statement affected an unexpected number of rows (0). After that I have surfed the stackoverflow, where someone suggested to make it another way, so i edited my SaveUser method

        public void SaveUser(UserProfile user)
     {
        var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter
                   )context).ObjectContext;
        try
        {
            objectContext.SaveChanges();
        }
        catch (OptimisticConcurrencyException)
        {
            objectContext.Refresh(RefreshMode.ClientWins, context.UserProfiles);
            objectContext.SaveChanges();
        }
     }

after these changes I don't get this error anymore, however my profile details are not changed.

My HttpPost Edit method(HttpGet retrieves correct information)

[HttpPost]
    public ActionResult Edit(UserProfile user)
    {
        if (ModelState.IsValid)
        {
            repository.SaveUser(user);
            return View(user);
        }
        return View();
    }

In my Edit view I have only LabelFor's and EditorFor's for everything(except Id,Username and Password) and Submit button.

Trying to solve that all day long and have not succeeded yet.

1
If your user object in the post method doesn't have the Id set, model binding won't work (aka nothing will be updated).dom
so, should I pass not the UserProfile object but rather the Id for that and then find the user with the Id passed? Or do I get it wrong?asdewka

1 Answers

2
votes

Most likely your user's primary key UserId property value is 0 because you don't use the UserId in your view. You are then trying to update an entity with key value 0 that doesn't exist in the database and causes the exception.

Put a hidden form field into your view that carries the user's UserId between client and server back and forth:

@Html.HiddenFor(model => model.UserId)

Normally if you use default routing you should have a route http://www.mysite.com/{controller}/{action}/{id}. If the url is then http://www.mysite.com/User/Edit/3 MVC tries to bind the value 3 to a property with name id (upper or lower case don't matter). Your Update should work then. But I guess your primary key property in User is not Id, but something else - like UserId. In that case the model binder can't find your key property and leaves its value as default (= 0).

Therefore as an alternative to the hidden field you could give the user's key property the name Id or specialize the route to use UserId as parameter.