I am using Entity Framework Core 3.1 with SQL Server.
I search how update column only for modified properties of a disconnected entity like :
public void UpdateOrderCustomer(int orderId, string customerName)
{
var order = new Order { Id = orderId };
using(var context = new MyDbContext())
{
context.Update(order);
order.Customer = customerName;
context.SaveChanges();
}
}
But this updates all order's column.
One solution is to load entity before update properties like :
public void UpdateOrderCustomer(int orderId, string customerName)
{
using(var context = new MyDbContext())
{
var order = context.Orders.Single(o => o.Id == orderId);
order.Customer = customerName;
context.SaveChanges();
}
}
But to load the entity, this executes an additional useless query.
I hoped there would be a BeginTracking method, but I haven't found this or any similar functionality.
How to update columns only for modified properties from a disconnected entity?
You can update a single property or a deattached entity like so:
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();
}
}
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