Search code examples
asp.netentity-frameworkasp.net-core

Entity Framework Core multiple connection strings on same DBContext?


I have an Asp.Net Core app with Entity Framework Core that I initialize as follows:

services.AddDbContext<ApplicationDbContext>(options => 
         options.UseSqlServer(sqlConnectionString));

This works fine, but I have a scenario where I need to read/write from the primary database for normal operations but for some operations I need to read from an alternate server (a replication target that's read only that we use for reporting).

With the way the new Core API does everything via Dependency Injection and configuration in StartUp.cs, how do I switch connection strings, but use the same ApplicationDbContext class?

I know that one option would be to have a duplicate of ApplicationDbContext class that I register with the DI system using a different connection string, but I'd like to avoid maintaining two identical DBContext objects just because sometimes I need to read from a different database server (but with the exact same schema).

Thanks in advance for any pointers!


Solution

  • 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")));
    
    }