1

I'm really new in this API development, so I have the next question.

Is it possible to get the DB name at run time for my connection string? This because the user will be sending the DB name through a Json file. I'm working with Visual Studio 2019, NetCore 3.1.

I have my appsettings.json like this:

"ConnectionStrings": {
    "ImportConnection": "Data Source=SQLSERVER;Initial Catalog={dbName};User ID=Id;Password=Pass;MultipleActiveResultSets=True"
  },

And my Startup.cs in configureservices I have this

services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ImportConnection")));

The user send a Json file with the next structure

{
    "ImportTypeId": 1,
    "Data": [
        {
            "LayoutID": 6,
            "ClientID": "XXX",

Where ClientID is the DB name.

I really want to know if there's a way to replace the Initial Catalog {dbName} in my connectionString with the ClientID value.

Also this is my DbContext

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace API_Test.Models
{
    public class ApplicationDBContext : IdentityDbContext<ApplicationUser>//DbContext
    {
        public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
        {

        }
        public DbSet<DataModel> API_DATA { get; set; }
    }
}

Thank you so much

4
  • According to your description, I couldn't understand your requirement clearly. Do you mean you have multiple connection string in your application? Like each user will contain his own connection string? Besides, since the appsetiting.json is a file and not support multiple thread modifying. So we couldn't modify the appsetting when there is a lot of requests sent to your server. Commented Aug 5, 2020 at 5:24
  • Can you be more specific on the statement, "The user will be sending the DB name through a Json file". Does it imply the user will send the json file via command line arguments to the application. Commented Aug 5, 2020 at 6:35
  • @BrandoZhang Thanks for your comment, I only have one connection string. The user have many databases in the same server, if he wants to import information to DB A, and later to DB B, he wants to send the DB name to use. I was thinking changing that at runtime. Don't know if is possible. Commented Aug 5, 2020 at 16:06
  • @DurgaPrasad Thanks for your comment,Yes the user will send the json fike via command line arguments Commented Aug 5, 2020 at 16:44

1 Answer 1

1

You can make use of the SqlConnectionStringBuilder class in conjunction with command line arguments to meet the requirement. The solution provided does not treat the command line input as a json though. It expects the input to be a normal command line parameter. I would recommend you to revisit that again and check if your user can convert the json to list of parameters and pass it along to application

So, lets say the user runs the application with following parameters:

dotnet run --ClientID XXX

Inside of Program.cs, ensure the commandline args are passed into the CreateDefaultBuilder() method, because this is the method which internally parses all the commandline args and adds them to the configuration object.

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

With that in place, you can now override the database value inside of your startup.cs as shown inline:

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("ImportConnection"));

if (!string.IsNullOrEmpty(Configuration.GetValue<string>("ClientID")))
{
    builder.InitialCatalog = Configuration.GetValue<string>("ClientID");
}

services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(builder.ConnectionString));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.