sqlentity-framework-4entityfielddbcontext

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..
}

Solution

  • Update: If you're using EF Core 7.0 or above, see this 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();
        }
    }