使用多个连接字符串

Using multiple connection strings

信息
我的解决方案中有多个项目,其中一个是 DAL,另一个是 ASP.NET MVC6 项目。 由于 MVC6 项目也是启动项目,因此我需要在那里添加我的连接字符串。

我看到了this solution,但是不接受,也不行。

我的尝试
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"
  }
}

Startup.cs

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 连接字符串访问数据时,我收到以下消息:

"Additional information: No connection string named 'FooBar' could be found in the application config file."

问题
如何让多个连接字符串工作?

如果您查看 asp.net 核心中的 official documentation for connection strings,他们的示例显示了存储在 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");

然后您需要为需要使用的所有连接字符串执行最后一点操作。