Skip to content

Run SQL Server script

Jon P Smith edited this page Nov 9, 2021 · 2 revisions

7. A tool for applying a SQL script file to a EF Core database

The ExecuteScriptFileInTransaction extension method will do what method name says. The format of the file is important - each SQL command must end with GO at the start of the line after the command.

Here is an example using this method

[Fact]
public void TestApplyScriptOneCommandToDatabaseOk()
{
    //SETUP
    var options = this.CreateUniqueClassOptions<EfCoreContext>();
    var filepath = TestData.GetFilePath("Script01 - Add row to Authors table.sql");
    using (var context = new EfCoreContext(options))
    {
        context.CreateEmptyViaWipe();

        //ATTEMPT
        context.ExecuteScriptFileInTransaction(filepath);

        //VERIFY
        context.Authors.Count().ShouldEqual(1);
    }
}
Clone this wiki locally