这个DbContext没有配置任何数据库提供程序。

7

我最近将我的项目更新到了最新版本的Entity Framework Core(+VS2017)。当我尝试更新数据库时,出现以下错误消息。虽然错误消息很清楚,但它似乎是错误的。在我的ConfigureServices中确实有AddDbContext(请参见下面的代码)。

我错过了什么?

错误信息

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

你的连接字符串是什么样子? - DavidG
这是连接字符串。我可以使用SSMS连接它。 "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-MG-5880417d-c8ef-4bc8-afc5-4a7f7c617d9b;Trusted_Connection=True;MultipleActiveResultSets=true" - Martin
@DavidG - 我在ApplicationDbContext中有两个ctor。一个是默认的(无参数),另一个是带有DBContextOptions的:publicApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) - Martin
@haim770 - 我的解决方案中有多个项目。但是,我正在运行dotnet ef命令,该命令在我的ApplicationDbContext所在的项目文件夹下运行。 - Martin
好的,连接字符串是在上下文项目中还是仅在使用者项目中? - DavidG
显示剩余4条评论
1个回答

22

您需要删除默认构造函数,也就是没有参数的构造函数。这样做后,所有的操作都将按预期进行。

注意:原因在于,运行时会调用无参构造函数,而不是public MyDbContext(DbContextOptions options) : base(options) {}


有趣,但如果你需要一个无参数的构造函数,这有点烦人... - DavidG
没错,如果您对此问题感兴趣,请查看Git:https://github.com/aspnet/EntityFramework/issues/4825 @DavidG 有很多选择。 - Sampath
2
太棒了!我在解决Asp.Net Core 1.1中迁移问题时,使用了一个解决方法来生成迁移代码,最终到了这里。我一直遇到“未配置数据库提供程序...”的错误,但是无法理解它的含义。最后,我来到这里并看到要从我的上下文中删除默认构造函数。就是这样!感谢@Sampath! - ih303
1
这不是与这个链接矛盾吗:https://dev59.com/ROk6XIcBkEYKwwoYBvXb - Marcus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接