views:

441

answers:

2

Can someone please check out this code, i really dont understand why i got violation of unique when i try to update an record. the code used to create new record work just fine, but when i try to use it to update, it called out violation.

Controller:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(User user)
    {
        if (ModelState.IsValid)
        {
            userRepository.SaveUser(user);
            return RedirectToAction("List");
        }
        else
            return View("Edit");
    }

userRepo:

    public void SaveUser(User user)
    {
        user.LAST_ACTIVITY = DateTime.Now;
        if (user.USER_ID != 0)
        {
            usersTable.Attach(user);
            usersTable.Context.Refresh(RefreshMode.KeepCurrentValues, user);
        }
        else
        {
            usersTable.InsertOnSubmit(user);
        }
        usersTable.Context.SubmitChanges();
    }

and i got an error:

Unable to refresh the specified object. The object no longer exists in the database.

when i try to change the userRepo like this for testing purpose.

    public void SaveUser(User user)
    {
        user.LAST_ACTIVITY = DateTime.Now;
        usersTable.Attach(user);
        usersTable.Context.Refresh(RefreshMode.KeepCurrentValues, user);
        usersTable.Context.SubmitChanges();
    }

Im wondering if there anyone on this board can find out if i am wrong somewhere in this problem :).

Thank you very much and wish you best regard. :)

A: 

Ignore ID on your model binding.

[Bind(Exclude= "Id")]
public ActionResult Edit(User user)

Kindness,

Dan

Daniel Elliott
this will not work since the ID is Int, and int is not a int is not a nullable type, and of course if it's set to exclude, it will be 0 by default. and if it's 0, new record will be create, instead of update the record. :)
DucDigital
+1  A: 

Looks like you have conflicts to resolve even though you're telling it to "KeepCurrentValues", try this before the submit changes...

foreach(ObjectChangeConflict conflict in usersTable.Context.ChangeConflicts)
{
    foreach(MemberChangeConflict memberConflict in conflict.MemberConflicts)
    {
        memberConflict.Resolve(RefreshMode.KeepCurrentValues);
    }
}
RailRhoad