解决  为什么startup.cs无法从appsettings.json中读取数据库连接字符串?

毁灭

活跃的成员
已加入
2020年3月28日
留言内容
36
编程经验
1-3
在尝试添加-删除迁移或更新数据库时遇到了这个问题,我花了近一周的时间来找到解决方法。由于某些原因,没有从appsettings.json文件或appsettings.environment.json文件中读取到本地SQL Server的连接字符串。我寻找了许多变通办法,但这是在我的startup.cs类中解决的:


startup.cs:
services.AddDbContextPool<ApplicationDbContext>(options =>
     options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=AstrologerDb;Trusted_Connection=True;MultipleActiveResultSets=true"));

以前是这样的:

startup.cs:
   services.AddDbContextPool<ApplicationDbContext>(options =>
     options.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]));

这是我尝试使用上述方法添加迁移时遇到的错误:

System.ArgumentNullException:值不能为null。
参数名称:connectionString
在Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(字符串值,字符串parameterName)
在Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder,String connectionString,Action`1 sqlServerOptionsAction)
在manglamastro.Startup。<ConfigureServices>C:\ Users \ dell-pc \ source \ repos \ manglamastro \ manglamastro \ Startup.cs中的b__2_0(DbContextOptionsBuilder选项):第27行
在Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions。<>c__DisplayClass3_0`2。<AddDbContextPool>b__0(IServiceProvider _,DbContextOptionsBuilder ob)
在Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions。<>c__DisplayClass5_0`2。<AddDbContextPool>b__0(IServiceProvider sp,DbContextOptionsBuilder ob)
在Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory [TContext](IServiceProvider applicationServiceProvider,Action`2 optionsAction)
在Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions。<>c__DisplayClass10_0`1。<AddCoreServices>b__0(IServiceProvider p)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处
在Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine。<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(类型serviceType,ServiceProviderEngineScope serviceProviderEngineScope)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider提供者,类型serviceType)
在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider提供程序)
在Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions。<>c__10`1.<AddCoreServices>b__10_1(IServiceProvider p)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite,ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处
在Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine。<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope范围)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(类型serviceType,ServiceProviderEngineScope serviceProviderEngineScope)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider提供者,类型serviceType)
在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider提供程序)
在Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetServices [T](IServiceProvider提供程序)
在Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
在Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(字符串名称)
在Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
在Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.RemoveMigration(String contextType,Boolean force)
在Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigrationImpl(String contextType,Boolean force)处
在Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigration中。<>c__DisplayClass0_1.<.ctor>b__0()
在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase中。<>c__DisplayClass3_0`1。<Execute>b__0()
在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase中。Execute(Action action)
值不能为空。
参数名称:connectionString


这是我的appsettings.json文件:

appsettings.json:
{
    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=AstrologerDb;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {

        "LogLevel": {
            "Default": "Warning"
        }
    }
}


我的program.cs

Program.cs:
namespace manglamastro
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            return new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
        }
    }
}



这是startup.cs

Startup.cs:
using manglamastro.Models;
namespace manglamastro
{
    public class Startup
    {
        private IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }
        
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit //go.microsoft.com/fwlink/?LinkID=398940
        public void 配置服务(IServiceCollection services)
        {
            services.AddScoped<IAstrologerRepository, SQLAstrologerRepository>();

            services.AddMvc();
            services.AddDbContextPool<ApplicationDbContext>(options =>
     options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=AstrologerDb;Trusted_Connection=True;MultipleActiveResultSets=true"));
          
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
          

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(name: "login",
                    template: "{controller=Home}/{action=Login}");
                
            });

        }
    }
}

从DesignTimeDbContextFactory.cs继承的ApplicationDBContext
ApplicationDbContext:
namespace manglamastro.Models
{
    public class ApplicationDbContext:DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {

        }

        public  DbSet<Astrologer> Astrologers { get; set; }
        public DbSet<Customers> Customers { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Specialization> Specializations { get; set; }


    }
}


这是DesignTimeDbContextFactory.cs

DesignTimeDbContextFactory.cs:
namespace manglamastro.Models
{
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json")
           .Build();
            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            builder.UseSqlServer(connectionString);
            return new ApplicationDbContext(builder.Options);
        }
    }
}


到目前为止,只有一个HomeController,并且与index.cshtml有一些共享视图。

是什么引起了这个问题,但又不允许我的startup.cs类从appsettings.json中读取?

我是一个初学者,所以如果不是很多,任何人都可以帮助我解决这个问题,以及如何让我的startup.cs从appsettings.json中读取连接字符串?将来会以某种方式影响我的项目吗?

这是我的项目结构:

devenv_nsO2BDPWOJ.png


















提前致谢

 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,497
地点
弗吉尼亚州切萨皮克
编程经验
10+
显然,在.NET Core 2.0(及更高版本)中 无证重大变更 to the WebHostBuilder() which causes it not to read the appsettings.json. It looks like the quickest way to fix things is to call CreateDefaultBuilder() as per the documentation:
 
最佳 底部