簡體   English   中英

無法使用連接字符串名稱運行支架 dbcontext

[英]Unable to get scaffold-dbcontext to run using connection string name

我有一個數據庫上下文,我正在嘗試使用數據庫腳手架進行更新。 我在 package 管理器控制台中使用的命令是:

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."

奇怪的是,這個上下文是使用這個命令生成的,所以我不確定為什么它現在會停止工作。 我可以通過在命令中使用完整的連接字符串而不是命名連接來輕松解決這個問題,但是隨后使用我希望避免的連接字符串生成數據庫上下文,因為您總是會收到這樣的警告:

#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“ConnectionStrings”中所做的操作。 該錯誤提到了 IConfiguration。 您可能缺少在 Startup class 中設置的連接。

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")));
          ...
    }...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM