skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have worked around this in a few ways.

    1. My test was connecting to the master database of the sql server testcontainer. This does not let you use Alter Database Current as its a system database.
    2. I use ALTER DATABASE CURRENT SET ENABLE_BROKER; to avoid having to specify the database name as string literal
    3. When trying to run the above ALTER statement during a migration, it still fails with the error described here however the workaround about single user mode didn't work for me. I had no choice but to not run this during a migration - instead when my test runs, I create a connection seperately and execute this command against the database, AFTER ef core migrations have run and the database is up to date, but before proceeding to run my test logic.

    This 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.


  2. 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

    declare @db sysname = db_name()
    
    declare @sql nvarchar(max) = 'alter database ' + quotename(@db) + ' set enable_broker'
    
    exec sp_executesql @sql 
    

    And ALTER DATABASE CURRENT exists for just this reason: to create DDL scripts that aren’t littered with the name of the current database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search