Change database on the fly EF Core

790 Views Asked by At

I need to create a context to a database given a key in the header of a request

The article I have found to do this uses a USE statement

These are not compatible with Azure SQL databases

public class DatabaseInterceptor : DbCommandInterceptor
{
    private readonly TenantInfo tenantInfo;
    public DatabaseInterceptor(TenantInfo tenantInfo)
    {
        this.tenantInfo = tenantInfo;
    }

    public override Task<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, 
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        //POtential solution
        command.Connection = new SqlConnection("MY CONNECTION STRING");

        //Recommended approach - wont work with Azure SQL
        command.CommandText = $"USE db_my_Test_{tenantInfo.Name} {command.CommandText}";

        return base.ReaderExecutingAsync(command, eventData, result);
    }
}

Im concerned about creating a new Db Connection for every single SQL query and whether it impacts the built in functionality of EF Core, such as tracking

Are there any alternatives?

I have access to the connection strings so I could potentially change the connection string as shown but Im not sure this is the best approach?

Im using .NET Core 3.1 with EF Core 3

Paul

0

There are 0 best solutions below