Efcore: NET Core CLI Cannot Find Connection String in appsettings.json When configuration property is not in sorted order in file

Created on 25 Apr 2017  路  12Comments  路  Source: dotnet/efcore

I'm working with a ASP.NET Core web application project that references another project with my DbContext. DBContextOptions are being configured in the dependency injection container.

When attempting to run dotnet ef migrations add it cannot find the connection string when the connection string property (i.e. "ConnectionStrings") in appsettings.json is not included in the file in sorted order.

Steps to reproduce

Running this command produces the error below: dotnet ef migrations add init --startup-project ..\DDATest.WebApp

Exception message:
Value cannot be null.
Parameter name: connectionString
Stack trace:
System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
   at DDATest.WebApp.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder e) in C:\Users\ddeangelis\Desktop\aspnetcore\DDATest.WebApp\DDATest.WebApp\Startup.cs:line 37
   at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitClosedIEnumerable(ClosedIEnumerableCallSite closedIEnumerableCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(String name)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

```c#
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(
            e =>
            {
                e.EnableSensitiveDataLogging();
                e.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}
```c#
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> dbco) :
        base(dbco)
    {

    }

    DbSet<Canto> Cantos { get; set; }
    DbSet<MirrorReading> MirrorReadings {get; set;}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

not working:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    },
    "ConnectionStrings": {
      "DefaultConnection": "Server = (localdb)\\mssqllocaldb; Database = testingv2; Trusted_Connection = True; "
    }
  }
}

working:

{
    "ConnectionStrings": {
        "DefaultConnection": "Server = (localdb)\\mssqllocaldb; Database = testingv2; Trusted_Connection = True; "
    },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
        "Default": "Warning"
    }
  }
}

Further technical details

EF Core version: 1.1
Microsoft.EntityFrameworkCore: version 1.1.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10 Pro
IDE: Visual Studio 2017

closed-external

Most helpful comment

@DJDA how did you fix this im getting same issue

{
  "ConnectionStrings": {
    "DefaultConnection":
      "Server=(localdb)\\mssqllocaldb;Database=Panda;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

All 12 comments

This looks more like a Configuration issue.

@DJDA In the one you say is not working, the connection string is nested under Logging. It wouldn't expect to be found there. This seems like it is by-design to me, but if you still feel there is an bug, then please file an issue in https://github.com/aspnet/Configuration

@ajcvickers Thanks! The JSON nesting mistake was the issue. Appreciate the response.

@DJDA how did you fix this im getting same issue

{
  "ConnectionStrings": {
    "DefaultConnection":
      "Server=(localdb)\\mssqllocaldb;Database=Panda;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Excelent. It helped me a lot.

Maybe we were all watching the same tutorial.

Thanks guys this fixed my issue...

i have some problem too

@omer-jan If you're still having problems here, then please file a new issue and include a small, runnable project/solution or complete code listing that demonstrates the behavior you are seeing.

In my case, it was caused because I missed adding this to appsettings.Development.json file. Please don't kill the newbie...

i have problem too asp.net Core 3.1 api

Can you help any one

PM> Add-Migration "InitialCreate"
Build started...
Build succeeded.
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction) at donetion.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder Options) in B:\Dotnetcore\donetion\donetion\Startup.cs:line 31 at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_02.b__0(IServiceProvider p, DbContextOptionsBuilder b)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptionsTContext

@ssukurulla

services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

If it is your code,
The appsettings.json file must contain connection string for this key 'DefaultConnection', please check it first.

I got the same issue

Was this page helpful?
0 / 5 - 0 ratings