How to automate DB setup of Entity Framework's Code First in TestContainers for testing?

Viewed 17

In order to setup the TestContainer's MsSqlTestcontainer for testing, I copied the script emitted by dotnet ef migrations script and planted it in the unit-test's setup (actual code doesn't :

void PrepareDb(MsSqlTestcontainer dbTestContainer){
    dbTestContainer.ExecScriptAsync(@"CREATE TABLE [DbName] ( /* ... */ )");
}

Is there a way to automate it, for instance if the DB model ever changes, and wire-up e.g. MyDbContext straight to the TestContainer's logic?

I was considering passing the MyDbContext code into the container and run dotnet ef migrations script inside of it, but I'm not sure how much it worth the effort (and I need to use a container that already has dotnet installed, which is another complication..).

That's the dbTestContainer setup, FWIW:

var dbTestContainer = new TestcontainersBuilder<MsSqlTestcontainer>()
    .WithDatabase(new MsSqlTestcontainerConfiguration { Password = "whatever secret" })
    .WithImage("mcr.microsoft.com/azure-sql-edge")
    .WithWaitStrategy(Wait.ForUnixContainer())
    .Build()
1 Answers

Connect to the containerized database and run migrations programmatically before tests start with

dbContext.Database.Migrate();

Related