ExecuteSqlRaw is an Entity Framework Core method for sending a raw SQL command directly to the underlying database. It bypasses the ORM when a database-specific operation has no managed EF Core equivalent. section 5.3.6
During board-game database seeding, it enables SQL Server’s IDENTITY_INSERT setting so imported records can preserve their existing IDs. The setting is turned on before saving entities and off afterward. section 5.3.6
A safe implementation follows three coordinated steps:
- Begin a database transaction. section 5.3.6
- Execute SET IDENTITY_INSERT BoardGames ON, then save the entities. section 5.3.6
- Execute SET IDENTITY_INSERT BoardGames OFF and commit the transaction. section 5.3.6
Preserving IDs during seeding
using var transaction = _context.Database.BeginTransaction(); _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT BoardGames ON"); await _context.SaveChangesAsync(); _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT BoardGames OFF"); transaction.Commit(); section 5.3.6
// SAVE
using var transaction = _context.Database.BeginTransaction();
_context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT BoardGames ON");
await _context.SaveChangesAsync();
_context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT BoardGames OFF");
transaction.Commit();
Shows the complete transactional command sequence for enabling identity insertion, saving entities, disabling it, and committing. section 5.3.6
