2016-11-22 38 views
5

我最近將項目更新爲最新版本的Entity Framework Core(+ VS2017)。當我嘗試更新數據庫時,出現以下錯誤消息。錯誤消息很明顯,但似乎是錯誤的。我的ConfigureServices中有AddDbContext(請參閱下面的代碼)。沒有爲此DbContext配置數據庫提供程序

我錯過了什麼?

錯誤

> dotnet ef database update --verbose 

Finding DbContext classes... 
Using context 'ApplicationDbContext'. 

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext. 

啓動

public void ConfigureServices(IServiceCollection services) { 
    services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection"))); 

的csproj

<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore"> 
    <Version>1.1.0</Version> 
</PackageReference> 
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore"> 
    <Version>1.1.0</Version> 
</PackageReference> 
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer"> 
    <Version>1.1.0</Version> 
</PackageReference> 
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design"> 
    <Version>1.1.0</Version> 
    <PrivateAssets>All</PrivateAssets> 
</PackageReference> 
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools"> 
    <Version>1.0.0-msbuild1-final</Version> 
    <PrivateAssets>All</PrivateAssets> 
</PackageReference> 
<PackageReference Include="Microsoft.EntityFrameworkCore.Design"> 
    <Version>1.1.0</Version> 
</PackageReference> 
+0

你的連接字符串是什麼樣的? – DavidG

+0

並且你的上下文在其構造函數中有'DbContextOptions '對象嗎? – DavidG

+0

這是連接字符串。我可以通過SSMS連接到它。 「DefaultConnection」:「Server =(localdb)\\ mssqllocaldb; Database = aspnet -MG-5880417d-c8ef-4bc8-afc5-4a7f7c617d9b; Trusted_Connection = True; MultipleActiveResultSets = true」 – Martin

回答

15

你必須刪除默認構造函數。換句話說,參數less構造函數。之後,所有將按預期工作。

注意:原因是,在運行時調用參數less構造函數而不是此public MyDbContext(DbContextOptions options) : base(options) {}

+0

有趣的,有點討厭,但如果你需要一個無參數的構造函數... – DavidG

+0

是的,這是真的。如果你有興趣知道更多關於這個問題,請參閱Git:https://github.com/aspnet/EntityFramework/問題/ 4825 @DavidG有很多選擇。 – Sampath

+2

令人驚歎!在解決Asp.Net Core 1.1中的遷移問題並使用[解決方法](https://github.com/aspnet/Tooling/blob/master/known-issues-vs2017.md#publishing-project) -with-entity-framework-migration-failures)生成遷移代碼。我一直在收到「沒有數據庫提供程序已配置...」一段時間的錯誤,無法做到正面或反面。最後,我在這裏登陸並看到**從我的上下文中刪除默認構造函數**。就是這樣!謝謝@Sampath! – ih303

相關問題