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;
}
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 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.
Try this:
using (var _cnt = new STQContext())
{
_cnt.Users.Attach(user);
_cnt.Entry<User>(user).Property(u => u.PasswordHash).IsModified = true;
_cnt.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With