我有一个数据库上下文,我试图使用DB脚手架更新。我在包管理器控制台使用的命令是:
Scaffold-DbContext Name="pwa_db" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data -Force
我appsettings。Json是这样的:
"ConnectionStrings": {
"pwa_db": "Server=[My Server];Database=[My DB];Trusted_Connection=True;MultipleActiveResultSets=true"
}
然而,当我运行命令时,我得到这个错误:
"A named connection string was used, but the name 'pwa_db' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information."
奇怪的是,这个上下文是使用这个命令生成的,所以我不确定为什么它现在会停止工作。我可以通过在命令中使用完整的连接字符串而不是命名的连接来轻松解决这个问题但随后DB上下文会生成连接字符串这是我希望避免的因为你总是会得到这样的警告:
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
我不太关心警告本身,因为我使用的是可信连接,所以没有凭证被存储,我也不希望源离开我们的办公室。
谁能告诉我我可能需要查看的其他配置位或其他问题可能在发挥作用?因为我看不出任何消息中链接的文档有什么问题。
您是否尝试过将连接字符串添加到appsettings.development.json文件中?
我知道这是旧的,但也许这可以帮助别人。
它适用于我,我遵循你在脚手架命令和json " connectionstring "所做的。错误提到了IConfiguration。您可能错过了在Startup类中设置的连接。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<DTCCDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("pwa_db")));
...
}...