Search code examples
c#linqlinq-to-sqlsubmitchanges

LINQ: SubmitChanges() not updating my record


Not to sound like a broken record here (there a few posts that look like this one) but none of them seem to solve my problem. It seems that when you want to update

private bool resetPassword(string password)
{
    try
    {
       var db = new SchedulerDBDataContext();

       // since this is a instance method, I grab the ID from _this_
       AdminUser user = db.AdminUsers.SingleOrDefault(t => t.ID == _ID);

       if (user != null)
       {
           // this method DOES update these two fields.
           SchedUtil.md5Hash(password, ref user._EncryptedPassword, ref user._PasswordSalt);

           // I threw these in there to try something... it didn't work.
           //user._EncryptedPassword = user.EncryptedPassword;
           //user._PasswordSalt = user.PasswordSalt;

           // this DOESN'T do anything.
           db.SubmitChanges();
           return true;
       }

       return false;
    }
    catch (Exception)
    {
        return false;
    }
}

Maybe this a dumb question but I'm retrieving this from the db... why not just update this's properties. I'm guess I need to pull it through the DBContext I guess.


Solution

  • You should be setting the public properties and not the private values.

      // I threw these in there to try something... it didn't work.
           //user._EncryptedPassword = user.EncryptedPassword;
           //user._PasswordSalt = user.PasswordSalt;
    

    This won't trigger any updates.

    Even if you do :

          user.EncryptedPassword = user._EncryptedPassword;
          user.PasswordSalt      = user._PasswordSalt;
    

    this won't trigger any change either as you are not actually changing the values

    You can do something like

     string newEncryptedPassword;
     string newPasswordSalt;
    
     SchedUtil.md5Hash(password, ref newEncryptedPassword, ref newPasswordSalt);
    
     user.EncryptedPassword = newEncryptedPassword;
     user.PasswordSalt      = newPasswordSalt;
    

    Also check that your table has a primary key, otherwise Linq will not track the changes.