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