Initial db migration: No database provider has been configured for this DbContext

Viewed 168

I have the following DbContext class:

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);
    }
}

I registered the DbContext within the ConfigureServices method in StartUp.cs and added the connection string to appsettings.json

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

I tried to create the initial migration using the EF core command dotnet ef migrations add InitialCreate This resulted in the following error:

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 object in its constructor and passes it to the base constructor for DbContext.

The error message states that I should register the DbContext and add a DbContextOptions object in my constructor and pass it to the base constructor. I did all of that but unfortunately no luck. I cannot figure out what I am doing wrong.

1 Answers

The issue was that I ran the add migrations command from my entities project where the DbContext is located, but DbContext itself is only registered and created within the API project where my Startup.cs sits. The following command did the trick:

dotnet ef migrations add MigrationName -s mainProject -p DbContextProject

Check this Github issue for more details

Related