leora
leora

Reputation: 196539

Any reason why this LINQ to SQL update query is not working . .

Somehow this update code is not working:

Here is my Controller code:

    private UserRepository repo = new UserRepository();

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, UserInfo user_)
    {
        try
        {
            repo.UpdateUser(user_);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

Here is the repo code that is used above (UserRepository)

    private UsersDataContext db = new UsersDataContext();

    public void UpdateUser(UserInfo user_)
    {
        UserInfo origUser = GetUser(user_.Id);
        origUser.First = user_.First;
        origUser.Last = user_.Last;
        origUser.City = user_.City;
        origUser.Country = user_.Country;
        origUser.State = user_.State;
        origUser.Street_Address = user_.Street_Address;

        db.SubmitChanges();
    }

    public UserInfo GetUser(int id_)
    {
        return db.UserInfos.SingleOrDefault(d => d.Id == id_);
    }

EDIT:

Note that when debugging everything is running fine (no exceptions) but when it redirects back to Index the data has not been updated when the changes from the update.

Upvotes: 3

Views: 458

Answers (3)

name1ess0ne
name1ess0ne

Reputation: 928

Maybe you disabled Object Tracking?

Upvotes: 0

Paxxi
Paxxi

Reputation: 446

You don't mention how you've defined UserInfo, is it a struct or a class?

If it's a struct, returning it from GetUser will create a new object and thus you will not update the database object, only a local copy of it.

Moving the GetUser inline avoid this temp copy creation and that's likely why it's working.

afaik you could do something like

public void GetUser(int id_, out UserInfo user_)
{
    user_ = db.UserInfos.SingleOrDefault(d => d.Id == id_);
}

You would then call it like this

public void UpdateUser(UserInfo user_)
{
    UserInfo origUser;
    GetUser(user_.Id, out origUser);
    origUser.First = user_.First;
    origUser.Last = user_.Last;
    origUser.City = user_.City;
    origUser.Country = user_.Country;
    origUser.State = user_.State;
    origUser.Street_Address = user_.Street_Address;

    db.SubmitChanges();
}

Upvotes: 0

leora
leora

Reputation: 196539

i just changed the userrepository to the following:

private UsersDataContext db = new UsersDataContext();

public void UpdateUser(UserInfo user_)
{
    UserInfo origUser = db.UserInfos.SingleOrDefault(d => d.Id == id_);
    origUser.First = user_.First;
    origUser.Last = user_.Last;
    origUser.City = user_.City;
    origUser.Country = user_.Country;
    origUser.State = user_.State;
    origUser.Street_Address = user_.Street_Address;

    db.SubmitChanges();
}

so all i did was move the GetUser() method inline and it worked.

It might have been a red herring and it was just a caching issue . .

Upvotes: 1

Related Questions