How do I change connectionstring at runtime in EF7 Core?

c# entity-framework-core

Question

I am building system where each customer will have it's own database. When a customer loggs in, I will use the domain name of the users email adress to decide what connectionstring it should use.

Today, the connectionstring is set in the startup.cs file but this is not going to work.

My question is this: What's the best way to implement a rule based connectionstring selection in EF Core?

After the user has logged in, that user should use the same Connection string during his/her entire session.

1
1
5/2/2016 8:24:34 AM

Accepted Answer

Store your connection string in a config file, in my case I'm using appsettings.json file.

var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionString = builder["Data:DefaultConnection:ConnectionString"];

var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(connectionString);

var context = new DataContext(optionsBuilder.Options);

and DataContext class:

public class DataContext: DbContext
{
    public DataContext(DbContextOptions options) : base(options)
    { 
    }
}

and also you can do it via dependency injection. for this sample I'm using Autofac :

create ConnectionString class:

public class ConnectionStringDto
{
    public string ConnectionString { get; set; }
}

Autofac config:

var configBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionString = new ConnectionStringDto { ConnectionString = configBuilder ["Data:DefaultConnection:ConnectionString"]; };

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterInstance(connectionStringDto).AsSelf().SingleInstance();
containerBuilder.RegisterType<DataContext>().AsSelf().InstancePerLifetimeScope();

and DataContext class:

public class DataContext : DbContext
{
    private readonly ConnectionStringDto _connectionString;

    public DataContext(ConnectionStringDto connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(_connectionString.ConnectionString);
    }
    .
    .
    .
1
5/7/2016 7:16:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow