admin: fix AddCard inserting 0 rows (EF ValueGeneratedOnAdd sentinel mismatch)

PrebuiltDeckCard.Id is configured as ValueGeneratedOnAdd; EF's sentinel for
Guid is Guid.Empty. When a new entity with Id = Guid.NewGuid() is added to
the tracked ObservableHashSet (_deck.Cards), EF interprets the non-empty Guid
as an existing row and tracks the entity as Modified instead of Added.
SaveChangesAsync then issues an UPDATE that finds 0 rows →
DbUpdateConcurrencyException.

Fix: call Db.Entry(entry).State = EntityState.Added immediately after adding
to the collection for existing (tracked) decks. For new decks the plain
List<> is not yet tracked so graph traversal in SaveAsync handles it.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-01 11:11:27 -05:00
co-authored by Claude Happy
parent 2643fe4276
commit 9c4a1db8b1
@@ -355,13 +355,23 @@ else
private void AddCard(CardDefinition card) private void AddCard(CardDefinition card)
{ {
if (_deck!.Cards.Any(c => c.CardDefinitionId == card.Id)) return; if (_deck!.Cards.Any(c => c.CardDefinitionId == card.Id)) return;
_deck.Cards.Add(new PrebuiltDeckCard var entry = new PrebuiltDeckCard
{ {
CardDefinitionId = card.Id, CardDefinitionId = card.Id,
CardName = card.Name, CardName = card.Name,
Quantity = 1, Quantity = 1,
PrebuiltDeckId = _deck.Id, PrebuiltDeckId = _deck.Id,
}); };
_deck.Cards.Add(entry);
// When the deck is already tracked, _deck.Cards is EF's ObservableHashSet.
// Adding an entity with a non-empty Guid (ValueGeneratedOnAdd sentinel = Guid.Empty)
// causes EF to classify the entity as Modified (existing row) rather than Added (new row),
// so SaveChangesAsync issues an UPDATE that finds 0 rows → DbUpdateConcurrencyException.
// Forcing EntityState.Added here ensures EF generates an INSERT instead.
// For new decks (_isNew) the collection is a plain List not yet tracked by EF,
// so the graph traversal in SaveAsync handles it correctly without this override.
if (!_isNew)
Db.Entry(entry).State = EntityState.Added;
_cardSearch = string.Empty; _cardSearch = string.Empty;
_cardResults.Clear(); _cardResults.Clear();
} }