Asp.net core ASP.NetCore 2.x脚手架数据库和appsettings.json
ASP.NetCore 2.x,VisualStudio 2019 嗨 我试图阅读有关配置的.NetCore文档,但我遗漏了一些内容。我有一个使用三个数据库的项目。文档告诉我,我现在必须自己“搭建”DB cpnnections,运行如下操作:Asp.net core ASP.NetCore 2.x脚手架数据库和appsettings.json,asp.net-core,Asp.net Core,ASP.NetCore 2.x,VisualStudio 2019 嗨 我试图阅读有关配置的.NetCore文档,但我遗漏了一些内容。我有一个使用三个数据库的项目。文档告诉我,我现在必须自己“搭建”DB cpnnections,运行如下操作: Scaffold-DbContext -Connection "Server=my-db.company.edu;Initial Catalog=MyDB;Integrated Security=True" -Context MyThingsCon
Scaffold-DbContext -Connection "Server=my-db.company.edu;Initial Catalog=MyDB;Integrated Security=True" -Context MyThingsContext -Schemas "dbo" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models\MyThings
这很有效。我得到数据库上下文和相关的模型文件。我还得到了MythingContext.cs
文件,其中包含:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
if (!optionsBuilder.IsConfigured) {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=my-db.company.edu;Initial Catalog=MyDB;Integrated Security=True");
}
}
注意:上面的#警告…
行。我实际上做了三次DB脚手架,一次是针对三个不同的DB。其中两个…Context.cs
文件有#warning…
行,但其中一个有相同的注释,但格式为//warning…
在构建阶段,我在上面的代码注释中得到了两个#warning…
s,但没有得到//warning
#
和/
警告版本是否正常?这是生成的代码,所以我不应该弄乱它
接下来,由于它警告我将连接字符串移出代码,所以在我将连接字符串放入appsettings.json
后,我是否可以删除onconfigurang
方法
是否有其他/更好的方法来进行数据库搭建?最好针对您的特定环境使用配置文件
appsettings.Development.json
,appsettings.Production.json
等
例如:
appsettings.Development.json
{
"ConnectionStrings": {
"MyThingsDatabase": "Server=development-db.company.edu;Initial Catalog=DevelopmentDB;Integrated Security=True"
},
}
{
"ConnectionStrings": {
"MyThingsDatabase": "Server=production-db.company.edu;Initial Catalog=ProductionDB;Integrated Security=True"
},
}
appsettings.Production.json
{
"ConnectionStrings": {
"MyThingsDatabase": "Server=development-db.company.edu;Initial Catalog=DevelopmentDB;Integrated Security=True"
},
}
{
"ConnectionStrings": {
"MyThingsDatabase": "Server=production-db.company.edu;Initial Catalog=ProductionDB;Integrated Security=True"
},
}
然后在Startup.cs ConfgureServices方法中:
services.AddDbContext<MyThingsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyThingsDatabase"));
services.AddDbContext(选项=>
使用SQLServer(Configuration.GetConnectionString(“MyThingsDatabase”);
有无数种方法可以指定工作环境。
是的,在OnConfigurang方法中直接使用ConnectionString不仅是设计的不灵活性,而且如果使用用户名/密码组合,可能会导致安全漏洞。
您应该对任何连接字符串使用appsettings.json,并将适当的字符串传递给该dbContext的配置。不应该是
appsettings.Development.json
,appsettings.Production.json
(通常appsettings..json)
?是的,对不起。现在已经修好了。我想我很早就回忆起他们使用连字符的情景,我从来没有忘记过这一点。:)谢谢大家。。。其中一个问题是关于脚手架模型的。既然连接字符串是由scaffold系统在该代码中生成的,那么我应该删除该代码吗?有没有办法将连接字符串释放出来?@7Reeds scaffold不会为您执行配置文件或startup.cs代码。您必须手动移动它,然后删除onconfig方法。您必须将连接字符串传递给scaffolding CLI命令,以便它可以连接到数据库并查看您的模式,以便生成模型和上下文。