我在控制台应用程序中使用 Entity Framework 6 从 SQL Server 搭建现有数据库时遇到了一个“小”问题...
我在
App.config
中的连接字符串是:
<connectionStrings>
<add name="connString"
connectionString="Server=MyServer; Database=MyDb;User Id=MYUser ; Password=MyPW ; MultipleActiveResultSets=true;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
如果我尝试使用此命令构建我的数据库:
Scaffold-DbContext -Connection name=connString Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force
或
Scaffold-DbContext -Connection name=connectionString Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force
或
Scaffold-DbContext "Name=connectionStrings:connString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force
控制台总是返回错误:
使用了命名连接字符串,但在应用程序的配置中找不到名称“.......”。请注意,仅在使用“IConfiguration”和服务提供程序时才支持命名连接字符串,例如在典型的 ASP.NET Core 应用程序中。请参阅 https://go.microsoft.com/fwlink/?linkid=850912 了解更多信息。
所以我尝试使用明文连接字符串搭建脚手架,它没有返回任何错误,但只返回建议:
为了保护连接字符串中潜在的敏感信息,您应该将其从源代码中移出。您可以使用 Name= 语法从配置中读取连接字符串,从而避免搭建连接字符串 - 请参阅https://go.microsoft.com/fwlink/?linkid=2131148。有关存储连接字符串的更多指导,请参阅 http://go.microsoft.com/fwlink/?LinkId=723263。
所以我的问题是:
我应该怎么做才能只写我的连接字符串的名称,而不是明文的连接字符串?
提前致谢
在我的例子中(VS2022,.NET 6)我也遇到了同样的问题,并通过以下方式得到了解决方案;
试试这个:
Scaffold-DbContext 'Name=ConnectionStrings:YourConnectionName' Microsoft.EntityFrameworkCore.SqlServer ...