无法使用脚手架控制器-使用了命名的连接字符串,但是在应用程序配置中找不到名称DefaultConnection

问题描述

当尝试在项目中使用视图添加新控制器时,出现以下错误:(是的,该图像显示DEBUG连接...在截取错误屏幕快照后,将它们全部更改为DEFAULT)>

(如果图像不显示) 运行选定的代码生成器时发生错误:'使用了已命名的连接字符串,但是在应用程序的配置中找不到名称DefaultConnection。请注意,仅在使用“ IConfiguration”和服务提供程序时(例如在典型的ASP.NET Core应用程序中),才支持命名连接字符串。有关更多信息,请参见https://go.microsoft.com/fwlink/?linkid=850912

但是,我正在使用IConfiguration,并且Startup.cs和数据库上下文文件都引用了该连接。

在搭建dbcontext时,我可以使用DefaultConnection,它会从我希望在我的项目中看到的sql数据库提取所有更改-只是然后拒绝搭建控制器。

Startup.cs

        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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        services.AddDbContext<CJFresh>(options =>
                   options.UsesqlServer(
                       Configuration.GetConnectionString("DefaultConnection")));

数据库上下文文件

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UsesqlServer("Name=DefaultConnection");
        }
    }

AppSettings.json

    {
  "AllowedHosts": "*","ConnectionStrings": {

    "DefaultConnection": "Server=SERVER;Database=DATABASE;Trusted_Connection=False;user id=USERX;password=PASSWORDX;MultipleActiveResultSets=true",}
 }

我尝试了其他帖子中看到的一些解决方案,但它们似乎不适用于我。 例如,我已经尝试了这篇文章中的所有修改.Net Core 2 EF core connection string problem

我确定这很简单,但我现在看不到。

解决方法

我通过从 appsettings.json 复制整个 SQL Server 连接字符串并将其粘贴到 UseSqlServer 方法中来代替以下代码解决了这个问题。由于未知原因,Visual Studio 中的自动 Razor 视图构建向导不会从 json 连接字符串变量中读取。在我做了一个 scaffold-dbcontext 之后发生了这个错误,它从数据库表中创建了模型和一个 db 上下文类。

optionsBuilder.UseSqlServer("name=ACConnection");