EF4 Code First: how to update specific fields only

本小妞迷上赌 提交于 2019-11-30 15:21:29

问题


How do I update only certain fields on an entity?

I have a User entity like so:

public class User
{
    public string UserId { get; set; }
    public string PasswordHash { get; set; }
    public bool IsDisabled { get; set; }
    public DateTime AccessExpiryDate { get; set; }
    public bool MustChangePassword { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime LastActivity { get; set; }
}

So if for example, I want to update the user entity, but do not want to change the user password, how do I do that?

Currently, I'm using the following code to update entities:

using (var _cnt = new STQContext())
{
   _cnt.Entry<Item>(item).State = System.Data.EntityState.Modified;
   _cnt.SaveChanges();
   return;
}

回答1:


Try this:

using (var _cnt = new STQContext())
{
   _cnt.Users.Attach(user);
   _cnt.Entry<User>(user).Property(u => u.PasswordHash).IsModified = true;
   _cnt.SaveChanges();
}


来源:https://stackoverflow.com/questions/5374404/ef4-code-first-how-to-update-specific-fields-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!