I have an xunit test fixture that uses testcontainers
to spin up a docker container that is running sql server.
When my test runs, I’d like to use EF Core to migrate the database – I can do this no problem – I see the migrations run and the tables are created.
The problem comes where I need to amend the initial migration to run an Alter database statement to ENABLE_BROKER
.
This is because my test is testing an interaction with SqlDependency
which requires this to be switched on for the database.
The issue is that when modifying the migration class to execute custom sql as part of the migration, I cannot see how to get the current database name in order to form the required ALTER
sql.
I tried the following but the dbName
is always null
from this API and the api isn’t commonly used.
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
var dbName = this.TargetModel.GetDatabaseName();
migrationBuilder.Sql($"ALTER DATABASE {dbName} SET ENABLE_BROKER");
So how can we get the database name?
- EF Core 6.0
- Sql Server docker image: mcr.microsoft.com/mssql/server:2019-CU18-ubuntu-20.04
2
Answers
I have worked around this in a few ways.
master
database of the sql server testcontainer. This does not let you useAlter Database Current
as its a system database.ALTER DATABASE CURRENT SET ENABLE_BROKER;
to avoid having to specify the database name as string literalThis is all a workaround but the question of how to actually get the database name within an EF Core migration still stands, so if someone figures that out I will accept that as the answer.
I think ALTER DATABASE CURRENT is the correct answer. Obviously, you could sniff the current DB_NAME() and construct dynamic SQL in the migration custom SQL, but that’s just ugly. EG
And ALTER DATABASE CURRENT exists for just this reason: to create DDL scripts that aren’t littered with the name of the current database.