❔ Updating an entity/record with 1 query(?) on Entity Framework
My senior told me that there's a way to select and update something in EF in 1 query. So instead of this:
He said, if he remembers correctly, I should use the
Attach()
method. I've been Googling, and this is how I understood how to use this method:
Just wondering if my approach and understanding of the Attach()
method are correct.11 Replies
I would not recommend using attach and modifying the state direction. I wouldn't be suprised if that wiped all the other fields.
If your on ef core 7, there are built in methods to do this, otherwise linq2db offers some extension methods to do this as well without having to manually play with the change tracker
I'm curious why he would suggest this, instead of just doing the first approach. Is the first approach not optimized or something?
it just has an extra database call
Doing
SELECT
and UPDATE
instead of just UPDATE
?So I ended up seeing
Entry()
method as well, and this SO answer says that's the one that updates all fields, and Attach()
is actually the safer method.
https://stackoverflow.com/a/30988176Stack Overflow
DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState...
When I am in a detached scenario and get a dto from the client which I map into an entity to save it I do this:
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
What is the
ExecuteUpdate()
in EF Core 7Looks like I'm on EF Core 5
You have two choices then. One involves fetching and saving, one involves attaching an entity
First choice is more proper but takes two db calls
Second opens you up for a lot of issues, but saves you a db call
or use linq2db extensions to do it
Or that, yea
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.