How to update only one field using Entity Framework?

h3n picture h3n · Sep 4, 2010 · Viewed 219.9k times · Source

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

Stuart picture Stuart · Apr 6, 2011

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();
    }
}