Using multiple connection strings Using multiple connection strings json json

Using multiple connection strings


If you take a look at the official documentation for connection strings in asp.net core their example shows the connection string stored in appsettings.json like this

{  "ConnectionStrings": {    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"  },}

Which, when adapted to your example would become.

{  "ConnectionStrings": {    "DefaultConnection": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true",    "FooBar": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true"  }}

Configuring the context in Startup.cs with the configuration string being read from configuration would use the GetConnectionString() method with the configuration key

public void ConfigureServices(IServiceCollection services) {    // Add framework services.    services        .AddEntityFramework()        .AddSqlServer()        .AddDbContext<ApplicationDbContext>(options =>            options.UseSqlServer(Configuration.GetConnextionString("DefaultConnection")))        .AddDbContext<ApplicationDbContext>(options =>            options.UseSqlServer(Configuration.GetConnextionString("FooBar")));}

Now one observed issue with how the above context is configured in the original question is that there are now two connection strings for the same context.

Trying to use multiple connection strings to work for the same context will cause problems as the framework would not know which option to use when requesting the context.


what you need for configuration in .net core 3.x is something like thisor you have Iconfiguration injected in startup (This is for a command line project with args).

        IConfiguration Configuration = new ConfigurationBuilder()       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)       .AddEnvironmentVariables()       .AddCommandLine(args)       .Build();        string conString = Microsoft               .Extensions               .Configuration               .ConfigurationExtensions               .GetConnectionString(Configuration, "ConnectionName");

and then you need to do this last bit for all connection strings you need to use.