← All writing
/writing

EF Core: Why Your New Child Row Becomes a Phantom UPDATE

This one has bitten me on three different entity types in the same codebase, which is how I learned it's structural rather than careless.

The setup

A sensible base entity generates its own identity, so an object is fully-formed before it's persisted:

public abstract class Entity
{
    public Guid Id { get; protected set; } = Guid.NewGuid();
}

The problem

Add a child to a tracked parent's collection and EF Core inspects it. The key is populated, so change detection concludes this is an existing row and marks it Modified.

var order = await db.Orders.Include(o => o.Lines).FirstAsync(...);
order.AddLine(sku, quantity);   // Id assigned in the constructor
await db.SaveChangesAsync();    // issues UPDATE, not INSERT

EF issues an UPDATE against an id that isn't in the table. Zero rows affected, and you get:

The database operation was expected to affect 1 row(s), but actually affected 0 row(s).

A concurrency error, for a row that has never existed. The message points at optimistic concurrency, which is not the problem, and you lose an hour.

The fix

Register the child explicitly:

var line = order.AddLine(sku, quantity);
db.OrderLines.Add(line);            // now it's Added, not Modified
await db.SaveChangesAsync();

Making it hard to forget

The habit doesn't stick, so lean on the API instead. Have methods that create children return what they created — a method returning OrderLine invites the caller to do something with it, where a void method looks finished.

Then put the explanation on Entity.Id itself, where the cause lives. The person who hits this will be reading the stack trace, not your wiki.

← All writing