Info
我的解决方案中有多个项目,其中一个是 DAL,另一个是 ASP.NET MVC6 项目。
由于 MVC6 项目也是启动项目,我需要在其中添加连接字符串。
I saw 这个解决方案,但不被接受,也不起作用。
My Try
应用程序设置.json
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"FooBar": {
"ConnectionString": "Server=.\\SQLEXPRESS;Database=Bar;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
启动.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
连接字符串我收到以下消息:
“附加信息:无法连接名为“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")));
}
现在,在原始问题中如何配置上述上下文的一个观察到的问题是,现在同一上下文有两个连接字符串。
尝试使用多个连接字符串来处理同一上下文会导致问题,因为框架在请求上下文时不知道使用哪个选项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)