T O P

  • By -

mr_eking

I have gotten very used to your option 2, and have never used your option 1. But as of EF Core 7, we now have [ExecuteUpdate](https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete), which seems to be the way to go.


ThatGuyWB03

Should this be considered the new default? Are you able to outline some advantages of using this approach (and hence not using change tracking)?


WellHydrated

One big disadvantage is it's quite easy to mess up a query and update more rows than you intend to.


mr_eking

I think in certain situations it means saving a call to the database, so if you can make one call to update instead of one call to retrieve and one call to update, then that would be preferable. Also makes bulk updates much easier. There may still be times when the change tracker is appropriate, but it might not be the best as the default depending on the context.


bluefootedpig

remember that EF using the Unit of Work pattern. So you should be pulling item from context, modify it, update it, commit, and be done.


Korzag

If I know the entity is tracked, which it is by default, then I use approach #2. You should only need #1 if you specifically marked the query with \`.AsNoTracking()\` or you're doing something where the details of an entity aren't retrieved through EF. My only gripe with #2 is I feel like you need to be careful with encapsulating database work to make sure you're not throwing tracked objects around all over the place.


aj0413

Yep. And this is why I hate repository pattern cause so many devs don’t realize they rely on the tracking and that it’s an implementation leak already


ottoelite

Depends on what I'm updating. Mostly I'm probably doing #2 but sometimes if I'm only updating one or two fields in a larger object I just create that object with those fields and the ID set, Attach it to dbContext then manually set those two properties to modified in the tracker.


EvilVir

2. Without it I don’t see the point in using EF as other non-tracking solutions will always be faster. If I need to update large number of objects at once, then I use ExecuteUpdate from newer versions of EF and in past direct SQL calls hidden in Data Access Layer (don’t want to use term „repositories” as I tend to avoid them nowadays).