开发者

EF4 Code First: how to update specific fields only

开发者 https://www.devze.com 2023-02-18 12:06 出处:网络
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; }

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 MustChangePasswo开发者_如何学Pythonrd { 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;
}


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消