I have an Asp.Net Core app with Entity Framework Core that I initialize as follows:
services.AddDbContext(options =>
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")));
}
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.
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 DbSet<Blog> Blogs { get; set; }
public 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>
{
protected BloggingContext(string connectionString) { _connectionString = connectionString; }
protected BloggingContext(DbContextOptions<T> options) : base(options) { }
}
public class MyBackupBloggingContext : BloggingContext<MyBackupBloggingContext>
{
protected MyBackupBloggingContext(string connectionString) { _connectionString = connectionString; }
protected MyBackupBloggingContext(DbContextOptions<T> 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")));
}