gpt4 book ai didi

c# - 使用多个连接字符串

转载 作者:太空狗 更新时间:2023-10-29 21:21:24 27 4
gpt4 key购买 nike

信息
我的解决方案中有多个项目,其中一个是 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."

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

最佳答案

如果你看一下 official documentation for connection strings在 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")));
}

现在观察到的关于如何在原始问题中配置上述上下文的一个问题是,现在有两个连接字符串用于同一上下文。

尝试使用多个连接字符串来处理相同的上下文会导致问题,因为框架在请求上下文时不知道使用哪个选项。

关于c# - 使用多个连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com