Skip to content Skip to sidebar Skip to footer

Change Sql Server Connection String Dynamically Inside An Asp.net Core Application

I open one database at the start, then need to open another database based on user selecting two values. The database selection has to be at run-time and will change every time. Ha

Solution 1:

As I figured out, you are using one DbContext class for each database. This way, look docs. Remove AddDbContext from Startup, remove OnConfiguring from DbContext and pass options to constructor.

publicclassBloggingContext : DbContext
{
    publicBloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Then write service providing DbContext:

publicinterfaceIBlogContextProvider
{
    BlogContext GetBlogContext(string connectionString);
}

publicclassBlogContextProvider : IBlogContextProvider
{
    BlogContext GetBlogContext(string connectionString)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
        optionsBuilder.UseSqlServer(connectionString);
        returnnew BlogContext(optionsBuilder);
    }
}

Add service in your Startup.cs:

services.AddScoped<IBlogContextProvider, BlogContextProvider>();

Now you can use DI

publicclassHomeController : Controller
{
    private IBlogContextProvider _provider;

    publicHomeController(IBlogContextProvider provider)
    {
        _provider = provider;
    }

    public ActionResult Index()
    {
        using (var context = _provider.GetBlogContext(<your connection string>))
        {
            //your code here
        }
        return View();
    }
}

EDIT: Of course, you can write ContextProvider as generic.

Post a Comment for "Change Sql Server Connection String Dynamically Inside An Asp.net Core Application"