簡體   English   中英

使用多個連接字符串

[英]Using multiple connection strings

信息
我的解決方案中有多個項目,其中一個是 DAL,另一個是 ASP.NET MVC6 項目。 由於 MVC6 項目也是啟動項目,我需要在那里添加我的連接字符串。

我看到了這個解決方案,但它不被接受,也不起作用。

我的嘗試
appsettings.json

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

啟動文件

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

然而,當我嘗試使用FooBar連接字符串訪問數據時,我收到以下消息:

“附加信息:在應用程序配置文件中找不到名為‘FooBar’的連接字符串。”

問題
如何讓多個連接字符串工作?

如果您查看 asp.net core 中連接字符串官方文檔,他們的示例顯示了存儲在appsettings.json中的連接字符串,如下所示

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

其中,當適應您的示例時將成為。

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

使用從配置中讀取的配置字符串在Startup.cs配置上下文將使用帶有配置鍵的GetConnectionString()方法

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")));
}

現在,在原始問題中如何配置上述上下文的一個觀察到的問題是,現在同一上下文有兩個連接字符串。

嘗試使用多個連接字符串來處理同一個上下文會導致問題,因為框架在請求上下文時不知道使用哪個選項。

您需要在 .net core 3.x 中進行配置,或者您在啟動時注入了 Iconfiguration(這是針對帶有 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");

然后您需要為需要使用的所有連接字符串執行最后一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM