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();
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加