如何使用实体框架只更新一个字段?

人气:328 发布:2022-10-16 标签: sql entity-framework-4 field dbcontext entity

问题描述

Here's the table

Users

UserId
UserName
Password
EmailAddress

and the code..

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

解决方案

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

699