I'm looking for a way to update a property of an entity by knowing its primary key, without first querying it.
The solution I've come up with is this one:
var order = new OrderEntity()
{
Id = 5
};
db.Orders.Attach(order).State = EntityState.Unchanged;
order.Name = "smth";
db.SaveChanges();
Which seems to work fine, as the generated SQL is exactly what I expect:
UPDATE "Orders" SET "Name" = @p0
WHERE "Id" = @p1;
Question: is this the correct way of doing it?
I can't find any confirmation about this in the official documentation, or anywhere else on the web actually. Similar questions are about Entity Framework (non-Core) and they seem to use different strategies, like setting EntityState.Modified instead of Unchanged. I tried that as well but it has the effect of updating all the properties, which is not what I want to achieve. So I'm wondering if there's something I'm missing about the solution above.
Thanks.
The documentation for DbContext.Attach Method says:
Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used.
[...]
For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state.
[...]
For entity types without generated keys, the state set is always Unchanged.
[...]
So setting the state to Unchanged is not even necessary.
But be careful. If you set e.g. order.Amount = 0m; to clear the amount, this will not work, as no change will be detected. Write
var order = new OrderEntity()
{
Id = 5,
Amount = 1.00m; // Dummy value unequal 0.00m
};
db.Orders.Attach(order);
// Make the change
order.Amount = 0.00m; // Now, this change will be detected.
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