Execute SQL and scripts

Use schema operations where they fit, and keep database-specific SQL explicit.

Examples use Classic and Fluent tabs. Your choice follows you through the manual.

Execute a statement

Raw SQL passes through to the selected database. It does not translate between dialects. Values from application input should be bound through a command; migration SQL is trusted application code.

A SQL data change

Classic

Database.ExecuteNonQuery("UPDATE Users SET Name = 'Unknown' WHERE Name IS NULL");

Fluent

migration.Execute.Sql("UPDATE Users SET Name = 'Unknown' WHERE Name IS NULL");

Inside Up() / BuildUp(MigrationBuilder migration)

Files and embedded resources

ExecuteScript reads a file; ExecuteResourceScript reads an assembly resource. Fluent equivalents capture script text as dedicated operations. Make files available at deployment and set resource names explicitly. Relative file paths are resolved against the process working directory.

Execute a SQL file

Classic

Database.ExecuteScript("Scripts/backfill.sql");

Fluent

migration.Execute.Script("Scripts/backfill.sql");

Inside Up() / BuildUp(MigrationBuilder migration)

Execute an embedded SQL resource

Classic

Database.ExecuteResourceScript(GetType().Assembly, "MyMigrations.Scripts.backfill.sql");

Fluent

migration.Execute.EmbeddedScript(GetType().Assembly, "MyMigrations.Scripts.backfill.sql");

Inside Up() / BuildUp(MigrationBuilder migration)

For the second example mark backfill.sql as an EmbeddedResource in the migration project and use its actual manifest resource name. Missing resources fail before script execution.

Client batch separators

The script APIs split standalone SQL Server GO lines, including optional line comments, while respecting strings, quoted identifiers and nested comments. GO repetition and SQLCMD directives fail before any batches execute. ExecuteNonQuery and Execute.Sql do not split client separators.

Other providers receive one command unless they implement IScriptBatchProvider. A database SQL file is not necessarily compatible with SQL*Plus, mysql-client or isql command syntax. Raw SQL also invalidates planned schema knowledge during SQL preview.