實體框架核心1.1.1 ArgumentNullException為連接字符串拋出

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

我在使用EF Core bsaed應用程序將ASP.NET添加到ASP.NET Core MVC時遇到問題,其中拋出了ArgumentNullException,並將Exception的Message屬性讀作“參數名稱:connectionString StackTrace:參數名稱:connectionString”。

我的應用程序遵循Tom Dykstra和Rick Anderson在docs.microsoft.com上的Contoso大學教程,網址為https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro https:// docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

當我嘗試使用添加控制器對話框通過“添加腳手架”對話框選擇“帶有視圖的MVC控制器,使用實體框架”來添加腳手架控制器時,使用以下設置:

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

單擊“添加控制器”對話框中的“添加”按鈕將為構建過程生成以下輸出,以便為控制器添加腳手架:

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命令行: - 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 15.1.548.43366版權所有(C)Microsoft Corporation。版權所有。命令行: - 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查找生成器'controller'...運行生成器'controller'...嘗試在內存中編譯應用程序嘗試找出模型和DbContext的EntityFramework元數據:學生值不能為null.Value不能為null。

參數名稱:connectionString StackTrace:參數名稱:connectionString

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

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

在Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String [] args)的ContosoUniversity.Startup.b__4_0(DbContextOptionsBuilder選項)

在Microsoft.Extensions.DependencyInjection.ServiceProvider的Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider提供程序)中的Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory [TContext](IServiceProvider applicationServiceProvider,Action`2 optionsAction)。位於Microsoft.Extensions.DependencyInjection的Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider提供程序)的Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider提供程序,類型serviceType)上的<> c__DisplayClass16_0.b__0(ServiceProvider提供程序)。 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitClosedIEnumerable(ClosedIEnumerableCallSi)中的ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider提供程序)在Microsoft.Extensions.DependencyInjection的Microsoft.Extensions.DependencyInjection.ServiceProvider。<> c__DisplayClass16_0.b__0(ServiceProvider提供程序)的Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite,ServiceProvider提供程序)處的te closedIEnumerableCallSite,ServiceProvider提供程序。位於Microsoft.EntityFrameworkCore.Design.Inign.DbContextOperations.FindContextTypes()的Microsoft.EntityFrameworkCore.Design.Internal上的Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T](IServiceProvider提供者)的ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider提供程序,類型serviceType)。 Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices.TryCreateContextUsingAppCo上的Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)中的DbContextOperations.FindContextType(String name) de(類型dbContextType,類型startupType)RunTime 00:00:17.43

appsettings.json中的連接字符串定義如下所示(使用localdb):

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

Startup類中的ConfigureServices()方法的實現如下所示:

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

    services.AddMvc();
}

作為使用SQL Server Express LocalDB的替代方法,我還嘗試使用類似於以下內容的連接字符串設置連接到名為ContosoUniversity1但沒有定義任何表的現有SQL Server數據庫,並且當我嘗試使用時仍然會收到相同的ArgumentNullException創建Controller,並在通過IISExpress運行MVC Web應用程序時:

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

我正在使用Visual Studio Community 2017的實際版本,並為ASP.NET Core和Entity Framework Core提供了以下NuGet包引用(取自針對PackageReferences的.csproj文件:

<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" />

任何有關如何解決此問題的建議或想法將不勝感激。

提前感謝您的時間,幫助和耐心。

熱門答案

調試啟動並確保Configuration.GetConnectionString("DefaultConnection")實際返回一個值。那是你應該先檢查的地方。

您會注意到它是null因為在設置文件中拼寫錯誤的ConnctionStrings

更改

"ConnctionStrings": {...
}, 

"ConnectionStrings": {...
}, 


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow