Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core : Update column only for modified properties from disconnected entity

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?

like image 604
vernou Avatar asked Oct 26 '25 06:10

vernou


1 Answers

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();
  }
}
like image 65
johnny 5 Avatar answered Oct 27 '25 20:10

johnny 5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!