在 app.config 中为 Scaffold-DbContext EF 6 命令使用名称connectionStrings

问题描述 投票:0回答:2

我在控制台应用程序中使用 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

所以我的问题是:

我应该怎么做才能只写我的连接字符串的名称,而不是明文的连接字符串?

提前致谢

sql-server entity-framework-6 console-application scaffolding
2个回答
2
投票

在我的例子中(VS2022,.NET 6)我也遇到了同样的问题,并通过以下方式得到了解决方案;

  1. 在 appsettings.json 文件中添加了连接字符串(附有屏幕截图)
  2. 运行命令:PM> Scaffold-DbContext name=StudentDbConnectionString TrustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
  3. 生成了相关的DbContext文件(附截图)
  4. 在program.cs文件中的Builder.Services中手动注册DbContext(附截图)
  5. 重建应用程序
  6. 运行应用程序并且之前实现的所有功能均已测试成功。

0
投票

试试这个:

Scaffold-DbContext 'Name=ConnectionStrings:YourConnectionName' Microsoft.EntityFrameworkCore.SqlServer ...
© www.soinside.com 2019 - 2024. All rights reserved.