Ошибка при выполнении add-migration net core 3

Я пытаюсь настроить новую базу данных / миграции с Entity Framework Core с net core 3, но как бы то ни было, следующая ошибка. с начальным добавлением-миграцией. Не могли бы вы мне помочь?

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

appsettings.json

{
  "connectionString": {
    "MyConnection": "data source=Localhost;Database=MyDataBase;User Id=MyUser;Password=MyPass;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "AllowedHosts": "*"
}

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        private void ConfigureJson(MvcNewtonsoftJsonOptions obj)
        {
            obj.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            obj.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string contactConnection = Configuration.GetConnectionString("MyConnection");
            services.AddDbContext<ApplicationContactDbContext>(options =>
                    options.UseSqlServer(contactConnection)
            );
            services.AddMvc()
                   .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                   .AddNewtonsoftJson(ConfigureJson);
           services.AddCors(options =>
            {
                options.AddPolicy("EnableCORS", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); });
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
             .AddJwtBearer(options =>
             {
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidateLifetime = true,
                     ValidateIssuerSigningKey = true,
                     ValidIssuer = "http://localhost:5000",
                     ValidAudience = "http://localhost:5000",
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKeyYoSoyExitoso@345"))
                 };
             });
            services.AddControllers();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

Это ошибка:

В файле настроек приложения попробуйте переименовать "connectionString" в "ConnectionStrings".


person Community    schedule 05.07.2019    source источник


Ответы (1)


У меня точно такая же проблема

person Base    schedule 05.07.2019
comment
Судя по полученной вами ошибке, это похоже на проблему с конфигурацией, а не на что-то конкретное в структуре сущностей. Судя по настройкам вашего приложения, этот ответ выглядит правильным. Отсутствует конкретная часть s в конце ConnectionString s. - person ; 06.07.2019
comment
System.ArgumentNullException: значение не может быть нулевым. Имя параметра: connectionString в Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty (строковое значение, String parameterName) в Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer (DbContextOptionsBuilder.UseSqlServer (DbContextOptionsBuilder.UseSqlServer (DbContextOptionsBuilder), DbContextOptionsBuilder.builder_Connect_Builder_ConnectionString) .DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory [TContext] (IServiceProvider applicationServiceProvider, Action_5_1.b__0 (IServiceProvider р) в Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory (factoryCallSite factoryCallSite, RuntimeResolverContext контекст) на Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor_6_2. VisitCallSite (ServiceCallSite callSite, аргумент TArgument) в Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve (ServiceCallSite callSite, ServiceProviderEngineScope sc ope) в Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine. ‹> c__DisplayClass1_0.b__0 (Область ServiceProviderEngineScope) в Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineEngineEngineScope.ServiceLookup.ServiceProviderEngine.GetServiceServiceProviderEngine.GetServiceServiceProviderEngine.GetService ServiceProviderEngineScope.GetService (Type serviceType) в Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (IServiceProvider provider, Type serviceType) в Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions. ‹> C__10_7_2.VisitCallSiteMain (ServiceCallSite callSite, аргумент TArgument) в Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache (ServiceCallSite callSite, RuntimeResolverContext контекст, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock LockType) в Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache (ServiceCallSite singletonCallSite, RuntimeResolverContext контекст) на Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor_8_2.VisitCallSiteMain (ServiceCallSite callSite, TArgument аргумент) в Microsoft. Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache (ServiceCallSite callSite, RuntimeResolverContext контекст, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock LockType) при Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache (ServiceCallSite singletonCallSite, RuntimeResolverContext контекст) на Microsoft.Extensions.DependencyInjection.ServiceLookup. CallSiteVisitor_9_1.b__0 () в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute (действие действия) Значение не может быть нулевым. Имя параметра: connectionString - person nahammel; 08.11.2019