0

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

    }
}
Skalar
  • 3
  • 1
  • 5
  • 1
    I'm not sure I would do this in the constructor for a db context: `Database.EnsureDeleted(); Database.EnsureCreated();` – Caius Jard Apr 30 '22 at 14:16
  • I would recommend that you take a look at https://stackoverflow.com/questions/38238043/how-and-where-to-call-database-ensurecreated-and-database-migrate – Maritim Apr 30 '22 at 14:20
  • @CaiusJard But `Database.EnsureDeleted()` and `Database.EnsureCreated()` not perform bcs constructor doesn't perform - it's my main problem – Skalar Apr 30 '22 at 14:23
  • Well, you do need to use this DbContext in something (like, put it as the parameter to a Controller constructor) before the DI container even has to make an instance of it.. DI doesn't just new() up objects/run a constructor for the fun of it.. – Caius Jard Apr 30 '22 at 14:27
  • If you are using Migrations, make sure you use the method .Migrate() or .MigrateAsync(), instead of EnsureCreated(). – Nikola Develops Apr 30 '22 at 14:29
  • @NikolaDevelops you want to Migrate() every time you create a DbContext?? I wouldn't do *any* of this in a context constructor – Caius Jard Apr 30 '22 at 14:29
  • I mean, it all depends on what he's trying to do. The .Migrate() method makes sure the Database is created and if it isn't it will create it, while also applying all migrations. How many times does he change his models? – Nikola Develops Apr 30 '22 at 14:36
  • *How many times does he change his models?* - no-one changes them so often that checking/making the db up to date is something that should be done every time a context is created. Application startup maybe – Caius Jard Apr 30 '22 at 14:49
  • @CaiusJard, I agree. He should change it. I'm just making sure he's using the right method for his case. – Nikola Develops Apr 30 '22 at 14:55
  • How do you know Skalar is a "he"? Prefer "they" :) – Caius Jard Apr 30 '22 at 15:02

1 Answers1

0

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
IKomarovLeonid
  • 352
  • 1
  • 9