EF Core - 该 DbContext 没有配置任何数据库提供程序

4

我是EF Core 1.0的新手。在进行数据库迁移时运行以下命令,出现以下错误:

命令

 migrations add ApplicationUserIsActive -c ApplicationDbContext

错误:

System.InvalidOperationException:未为此DbContext配置数据库提供程序。可以通过覆盖DbContext.OnConfiguring方法或使用应用程序服务提供程序上的AddDbContext来配置提供程序。如果使用AddDbContext,则还要确保您的DbContext类型在其构造函数中接受一个DbContextOptions对象,并将其传递给DbContext的基础构造函数。

StartUp.cs

public class Startup
{
    public IConfigurationRoot Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddEntityFrameworkSqlServer()
            .AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=employee;Trusted_Connection=True;MultipleActiveResultSets=true;")
       .UseInternalServiceProvider(serviceProvider));

        services.AddEntityFrameworkSqlServer()
            .AddDbContext<EmplooyeeDbContext>((serviceProvider, options) =>
options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=employee;Trusted_Connection=True;MultipleActiveResultSets=true;")
       .UseInternalServiceProvider(serviceProvider));

        services.AddTransient<IUserContext, SeedUserContext>();
    }

}

.csproj file

 <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0">
  <PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" Version="1.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />

然而,当我执行与其他 DBContext 相关的迁移命令,即 "EmplooyeeDbContext" 时,迁移命令可以正常工作。

我该如何解决这个问题?


你的.csproj文件长什么样子?你有一个对Microsoft.EntityFrameworkCore.SqlServer的包引用吗? - dbattaglia
是的,它包含所需的参考。 - Arayn
你尝试过先调用 ApplicationDbContext,然后再添加两个 AddDbContext 吗?看起来你正在相互覆盖。 - VMAtm
1个回答

11

我找到了问题所在,它是由"ApplicationDbContext"的默认构造函数引起的。删除"ApplicationDbContext"的默认构造函数后,一切都开始正常工作。

感谢您的支持。


如此简单,却很容易被包管理器命令行所忽略! - Trevor
2
如果我们移除默认构造函数,那么我们如何创建新的对象呢? - Chetan Chaudhari
@ChetanChaudhari 使用依赖注入 - iosamammohamed
谢谢!我花了好几个小时,这是多么愚蠢的事情啊。既然发生了奇怪的事情,有人能解释一下为什么会这样吗?背后的原理是什么? - Abdulkarim Kanaan

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