-1

I need to connect to few databases whos look the same. I want to pass ConnectionString name as parameter when I induce instance of DB connection.

Context Class

public class AppDbContext : DbContext
    {

        public AppDbContext(string test) : base(GetOptions(test))
        {

        }

        public DbSet<Cargo> Cargoes { get; set; }

        

        private static DbContextOptions GetOptions(string connectionString)
        {
            return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
        }

    }

Startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
            });
        }

Code

[HttpGet]
        public Cargo Get()
        {
            var test2 = new AppDbContext("TEST");
            return _appDbContext.Cargoes.FirstOrDefault(c => c.Code == "code");
        }

1 Answers1

-3

I think it's better to create a separate context:

public class AnotherContext : AppDbContext 
{
 
}

And now you can configure them:

services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("FirstConnStr")));

services.AddDbContext<AnotherContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("SecondConnStr")));
feihoa
  • 477
  • 4
  • 10