liveBook · Manning

ExecuteSqlRaw

As explained in Building Web APIs with ASP.NET Core

ExecuteSqlRaw is an Entity Framework Core method that executes a raw SQL command against the underlying database.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Demonstrates transactional implementation and verification but does not descend into method internals.
Examples
Uses SET IDENTITY_INSERT around SaveChangesAsync while importing board games with existing IDs.
What you can do after
Operate/configure transactional seeding that preserves explicit SQL Server identity values.
How it connects
Connects raw SQL execution with Entity Framework Core, ORM bypassing, SQL Server, transactions, and database seeding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.