'AddDbContext doesn't call DbContext constructor

I trying to build WebAPI with ASP.NET core. I created Models and db Context, but Context doesn't calling from Program.cs . Though I add it with help addDbContext. In another project it worked, but not here.

Perhaps I do not fully understand how DI works and need to do something else/change in context or in the parameters/determination of the context constructor

Program.cs:

using FootballWebAPI.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);



builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

string? ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<FootballAPIContext>(options => options.UseSqlServer(ConnectionString));


var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>endpoints.MapControllers());
app.UseAuthorization();

app.MapControllers();

app.Run();

And my Context:

using Microsoft.EntityFrameworkCore;

namespace FootballWebAPI.Models
{
    public partial class FootballAPIContext:DbContext
    {
        public FootballAPIContext(DbContextOptions<FootballAPIContext> options)
            : base(options)
        {
            Database.EnsureDeleted();
            Database.EnsureCreated();
        }
        public DbSet<Match> Matches { get; set; }
       

        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            if(!optionBuilder.IsConfigured)
                optionBuilder.UseSqlServer("Server= DESKTOP-1GRC7IR\\SQLEXPRESS;Database=FootballAPI; Trusted_Connection=True;MultipleActiveResultSets=true;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Match>();
            OnModelCreatingPartial(modelBuilder);
        }
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

    }
}


Solution 1:[1]

You have to use ef migrations. Please read this article for example: https://www.entityframeworktutorial.net/efcore/entity-framework-core-migration.aspx

  1. launch nuget console
  2. type add-migration init for you project with FootballAPIContext
  3. Make sure that new migration class has been generated
  4. Run app -> db should be created

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IKomarovLeonid