How to read a connectionString WITH PROVIDER in .NET Core?

前端 未结 4 889
-上瘾入骨i
-上瘾入骨i 2021-01-11 18:45

I added

.AddJsonFile(\"Connections.json\", optional: true, reloadOnChange: true)

in

 public Startup(IHostingEnvironment e         


        
4条回答
  •  天命终不由人
    2021-01-11 19:20

    An old question, but I was looking at this issue today and thought I'd share ...

    A Simple Alternative to Including ProviderName

    Here is a simple alternative that avoids custom extensions and altering the default ConnectionStrings configuration structure. It's based on how Microsoft includes a ProviderName for apps on Azure.

    The solution is to add a context related key in the ConnectionStrings section that specifies the ProviderName.

    AppSettings.json with SQLite provider:

    {  
      "ConnectionStrings": {
        "MyContext": "Data Source=c:\\MySqlite.db;Version=3;",
        "MyContext_ProviderName": "System.Data.SQLite",
      }
    }
    

    And in the C# code read the values with the GetConnectionString() method:

    var connectionString = Configuration.GetConnectionString("MyContext");
    var providerName = Configuration.GetConnectionString("MyContext_ProviderName") ?? "";
    
    if (Regex.IsMatch(providerName, "SQLite", RegexOptions.IgnoreCase)) 
    {
        builder.UseSqlite(connectionString);
    }
    else if (Regex.IsMatch(providerName, "Oracle", RegexOptions.IgnoreCase)) 
    {    
        builder.AddOracle(connectionString);
    }
    else if (... 
    

    Bonus - Connection String Prefixes

    Microsoft includes predefined prefixes for SQLClient and MySQL which will automatically include the provider name in the above format. However, these prefixes only work when added as environment variables, i.e., not in appsettings.json. For example, defining the connection string in launchSettings.json with the MYSQLCONNSTR_ prefix would populate both the connection string and provider name. For detains, see Configuration in ASP.NET Core and scroll down to Connection string prefixes

    launchSettings.json

    {
      "profiles": {
        "Development": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "",
          "environmentVariables": {
           "ASPNETCORE_ENVIRONMENT": "Development",
    
           // The prefix
           "MYSQLCONNSTR_MyContext": "Server=myServerAddress;Database=Green;Uid=myUsername;Pwd=myPassword;"
    
          }
        }
    }
    

提交回复
热议问题