Entity Framework Core multiple connection strings on same DBContext?
You'll need two DbContexts.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class MyBloggingContext : BloggingContext
{
}
public class MyBackupBloggingContext : BloggingContext
{
}
And you can register them like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyBloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<MyBackupBloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BackupConnection")));
}
Can be done like this(tested with .net core 3.1):
public abstract partial class BloggingContext<T> : DbContext where T : DbContext
{
private readonly string _connectionString;
protected BloggingContext(string connectionString) { _connectionString = connectionString; }
protected BloggingContext(DbContextOptions<T> options) : base(options) { }
public virtual DbSet<Blog> Blogs { get; set; }
public virtual DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
}
public class MyBloggingContext : BloggingContext<MyBloggingContext>
{
public MyBloggingContext(string connectionString) : base(connectionString) { }
public MyBloggingContext(DbContextOptions<MyBloggingContext> options) : base(options) { }
}
public class MyBackupBloggingContext : BloggingContext<MyBackupBloggingContext>
{
public MyBackupBloggingContext(string connectionString) : base(connectionString) { }
public MyBackupBloggingContext(DbContextOptions<MyBackupBloggingContext> options) : base(options) { }
}
And in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyBloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<MyBackupBloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BackupConnection")));
}
Connection string can be resolved using IServiceProvider
. In the example below I map query parameter to configuration from appsettings.json
, but you could inject any other logic you want.
services.AddDbContext<ApplicationDbContext>((services, optionsBuilder) =>
{
var httpContextAccessor = services.GetService<IHttpContextAccessor>();
var requestParam = httpContextAccessor.HttpContext.Request.Query["database"];
var connStr = Configuration.GetConnectionString(requestParam);
optionsBuilder.UseSqlServer(connStr);
});
?database=Connection1
and ?database=Connection2
in query will lead to using different connection strings. It is worth to provide default value, when parameter is missing.