Entity Framework Core 1.1.1 ArgumentNullException Thrown For Connection String

asp.net-core asp.net-mvc entity-framework entity-framework-core

Question

I'm having trouble adding a Controller to an ASP.NET Core MVC with EF Core bsaed application in which an ArgumentNullException is being thrown with the Exception's Message property reading as "Parameter name: connectionString StackTrace:Parameter name: connectionString".

My application is following the Contoso University Tutorial on docs.microsoft.com by Tom Dykstra and Rick Anderson at https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/introhttps://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

When I try to add a scaffolding controller by selecting "MVC Controller with views, using Entity Framework" through the Add Scaffold dialog for the Student class using the Add Controller dialog with the following settings:

Model class:            Student (ContosoUniversity.Models)
Data context class:     SchoolContext (ContosoUniversity.Data)
Views:                  [All of the following are checked]
                        Generate views
                        Reference script libraries
                        Use a layout page 
                        (The layout textbox is left empty as it is set in a Razor _viewstart file)
Controller name:        StudentController

Clicking the Add button in the Add Controller dialog results in the following Output for the build process for adding the scaffolding for the controller:

C:\Program Files\dotnet\dotnet.exe aspnet-codegenerator --project "C:\work\NET\ContosoUniversity\ContosoUniversity\ContosoUniversity.csproj" --no-build controller --force --controllerName StudentsController --model ContosoUniversity.Models.Student --dataContext ContosoUniversity.Data.SchoolContext --relativeFolderPath Controllers --referenceScriptLibraries --useDefaultLayout Command Line: --project C:\work\NET\ContosoUniversity\ContosoUniversity\ContosoUniversity.csproj --no-build controller --force --controllerName StudentsController --model ContosoUniversity.Models.Student --dataContext ContosoUniversity.Data.SchoolContext --relativeFolderPath Controllers --referenceScriptLibraries --useDefaultLayout Microsoft (R) Build Engine version 15.1.548.43366 Copyright (C) Microsoft Corporation. All rights reserved. Command Line: --no-dispatch --port-number 5716 --project C:\work\NET\ContosoUniversity\ContosoUniversity\ContosoUniversity.csproj --no-build controller --force --controllerName StudentsController --model ContosoUniversity.Models.Student --dataContext ContosoUniversity.Data.SchoolContext --relativeFolderPath Controllers --referenceScriptLibraries --useDefaultLayout --dispatcher-version 1.0.0-rtm-10308 Finding the generator 'controller'... Running the generator 'controller'... Attempting to compile the application in memory Attempting to figure out the EntityFramework metadata for the model and DbContext: Student Value cannot be null.Value cannot be null.

Parameter name: connectionString StackTrace:Parameter name: connectionString

at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName) at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()

at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction) at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)

at ContosoUniversity.Startup.b__4_0(DbContextOptionsBuilder options) at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

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.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.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.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices.TryCreateContextUsingAppCode(Type dbContextType, Type startupType) RunTime 00:00:17.43

My connection string definition in the appsettings.json reads as follows (using localdb):

"ConnctionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
}, 

The implementation for the ConfigureServices() method in the Startup class reads as follows:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<SchoolContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddMvc();
}

As an alternative to using SQL Server Express LocalDB, I've also tried using a connection string setting resembling the following that connects to an existing SQL Server database with the name ContosoUniversity1 without any tables defined, and still receive the same ArgumentNullException when I try to create the Controller, and when running the MVC web application through IISExpress:

"ConnctionStrings": {
    "DefaultConnection": "Server=Skittles;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
},

I'm using the actual release of Visual Studio Community 2017 with the following NuGet package references in place for ASP.NET Core and Entity Framework Core (taken from the .csproj file's for PackageReferences:

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />

Any suggestions or ideas on how I can resolve this issue would be greatly appreciated.

Thank you in advance for your time, help and patience.

1
2
3/27/2017 2:49:36 AM

Popular Answer

Debug startup and make sure that Configuration.GetConnectionString("DefaultConnection") is actually returning a value. that is where you should check first.

You will notice that is null because in the settings file you spelt the key wrong ConnctionStrings

Change

"ConnctionStrings": {...
}, 

To

"ConnectionStrings": {...
}, 
2
3/27/2017 4:16:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow