h3n h3n - 1 month ago 12
SQL Question

How to update only one field using Entity Framework?

Here's the table

Users

UserId
UserName
Password
EmailAddress


and the code..

public void ChangePassword(int userId, string password){
//code to update the password..
}

Answer

Ladislav's answer updated to use DbContext (introduced in EF 4.1):

public void ChangePassword(int userId, string password)
{
  var user = new User() { Id = userId, Password = password };
  using (var db = new MyEfContextName())
  {
    db.Users.Attach(user);
    db.Entry(user).Property(x => x.Password).IsModified = true;
    db.SaveChanges();
  }
}
Comments