How to update only one field using Entity Framework?

前端 未结 16 1463
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  盖世英雄少女心
    2020-11-22 09:43

    You can tell EF which properties have to be updated in this way:

    public void ChangePassword(int userId, string password)
    {
      var user = new User { Id = userId, Password = password };
      using (var context = new ObjectContext(ConnectionString))
      {
        var users = context.CreateObjectSet();
        users.Attach(user);
        context.ObjectStateManager.GetObjectStateEntry(user)
          .SetModifiedProperty("Password");
        context.SaveChanges();
      }
    }
    

提交回复
热议问题