【问题标题】:Initial db migration: No database provider has been configured for this DbContext初始数据库迁移:没有为此 DbContext 配置数据库提供程序
【发布时间】:2021-03-18 15:59:12
【问题描述】:

我有以下 DbContext 类:

public class BingoMasterDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Player> Players { get; set; }
    public DbSet<Game> Games { get; set; }

    public BingoMasterDbContext() { }

    public BingoMasterDbContext(DbContextOptions<BingoMasterDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasOne(user => user.Player)
            .WithOne(player => player.User)
            .HasForeignKey<Player>(player => player.UserId);
    }
}

我在 StartUp.cs 的 ConfigureServices 方法中注册了 DbContext,并将连接字符串添加到 appsettings.json

services.AddControllers();
services.AddDbContext<BingoMasterDbContext>(
    options => options.UseSqlServer(Configuration.GetConnectionString("Database")));

我尝试使用 EF 核心命令 dotnet ef migrations add InitialCreate 创建初始迁移 这导致了以下错误:

没有为此 DbContext 配置数据库提供程序。可以通过重写 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。

错误消息指出我应该注册 DbContext 并在我的构造函数中添加一个 DbContextOptions 对象并将其传递给基本构造函数。我做了所有这些,但不幸的是没有运气。 我无法弄清楚我做错了什么。

【问题讨论】:

  • 删除无参数构造函数(public BingoMasterDbContext() { }),问题就解决了。异常消息表明由于某种原因使用了构造函数,当然那里没有配置数据库提供程序。这么写,构造函数反正也没用。

标签: c# sql-server entity-framework-core


【解决方案1】:

问题是我从 DbContext 所在的实体项目中运行了添加迁移命令,但 DbContext 本身仅在我的 Startup.cs 所在的 API 项目中注册和创建。以下命令成功了:

dotnet ef migrations add MigrationName -s mainProject -p DbContextProject

查看Github issue了解更多详情

【讨论】:

    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2019-02-17
    • 2021-05-04
    • 2016-11-15
    • 2018-11-12
    • 2018-12-15
    相关资源
    最近更新 更多