Data

EF Core SaveChanges returns 0 and saves nothing: silent write bugs

DEV Community: #efcore Cường Ben
Data

A PUT endpoint answers 204 while the row stays untouched, because SaveChanges only persists what the change tracker saw: a global NoTracking default or AsNoTracking means no UPDATE is ever sent. The post explains the silent zero, the Update call that overwrites every column, and four checks that catch both.

Key points

  • SaveChanges persists what the change tracker holds, so an untracked entity produces no UPDATE at all.
  • A global QueryTrackingBehavior.NoTracking default silently turns every write into a zero result.
  • An entity loaded by a different DbContext instance is invisible to the context whose SaveChanges you call.
  • Building an entity from the request and calling Update writes every column, including ones the request never sent.
  • AsTracking() overrides a no-tracking default for one query, and the returned count can be logged.
  • For a single column, ExecuteUpdateAsync issues one UPDATE and returns the number of rows affected.

Real-world use

  • Teams that enabled a global no-tracking default for read-heavy APIs and now have write endpoints answering 204 without saving
  • Services that load an entity in a background job and then try to update it through a different DbContext
  • An orders API where a PUT carrying only status and note wipes discount and approvedBy through Update
  • Minimal API endpoints whose tests assert only the 204 status code and therefore miss both bugs

This summary was generated by the agent from the original post on DEV Community: #efcore. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message