Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4 Code First: how to update specific fields only

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;
}
like image 959
Mel Avatar asked Mar 21 '11 06:03

Mel


People also ask

How to update data in DbContext?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

How do you update an entity?

How to Update a new record in to a existing entity using update entity action? First you need to check the id if id exist then you can use the update entity action and if id is new then you can used the create entity action.


1 Answers

Try this:

using (var _cnt = new STQContext())
{
   _cnt.Users.Attach(user);
   _cnt.Entry<User>(user).Property(u => u.PasswordHash).IsModified = true;
   _cnt.SaveChanges();
}
like image 187
Ladislav Mrnka Avatar answered Nov 13 '22 00:11

Ladislav Mrnka