Skip to content

Run SQL Server script

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

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(2);
    }
}

Here is a simple example of what the SQL script should look like, with GO on a newline after each SQL command

INSERT INTO Authors (Name) VALUES('Row 1')
GO

INSERT INTO Authors (Name) VALUES('Row 2')
GO
Clone this wiki locally