DbInitializer .net Blazor - Startup.cs

Posted 213 days ago by Francois
Edited 213 days ago
0

We used to be able to add IDbInitializer as per the below example in the startup.configure method

example: public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDbInitializer dbInitializer)

and then call dbInitializer.Initialize(); method that handle our migrations and database seeding.

I see we can no longer have the startup.configure method in.Net6. Is there a way to still accomplish this?

 

Ps. Sorry I posted in the wrong section  

Regards

Francois

 

 

 

  • 0

    .Net 6 has taken an approach that is considered more modern and simplistic, and they moved everything to the Program.cs file. While I haven't tried it in .Net 6, you should be able to do something like this in Program.cs

    ...
    
    var app = builder.Build();
    
    // Initialize the database
    var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
    using (var scope = scopeFactory.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    
        if (context.Database.EnsureCreated())
        {
            SeedAbout.Initialize(context);
        }
    }
    
    ...
    
    app.Run();

    And the SeedAbout class would just be something like:

    public class SeedAbout
    {
        public static void Initialize(ApplicationDbContext context)
        {
            var about = new AboutModel()
            {
                PageTitle = "About Me",
                Title = "About",
                Details = "Some general details..."
            };
    
            context.About.Add(about);
            context.SaveChanges();
        }
    }

    With that said, if you wanted an app to work the old way, they should still work. I believe you'll just need to setup your Program.cs and Startup.cs files in the previous manner, based off a previous template.

    Posted 213 days ago by selliott Edited 213 days ago
  • 0

    Thank you managed to get it going 

    Posted 213 days ago by Francois
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 1
An error has occurred. This application may no longer respond until reloaded. Reload đź—™