0

I want to automatically create the database and table structures when my desktop app is first run.
I can't find any examples or documentation on something equivalent for EFCore.
I did everything as it is in this documentation: https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-example.html
But I still have a problem: Exception thrown: 'Microsoft.Data.SqlClient.SqlException' in Microsoft.Data.SqlClient.dll, and empty database :( Please help me, if you can.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            try
            {
                optionsBuilder.UseMySQL("server=localhost;userid=root;password=topSecret;database=kartoteka-pracownicza");               
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again");
                        break;
                }
            };
        }
Saltwater
  • 1
  • 1
  • In the link provided the database is created with context.Database.[EnsureCreated](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated?view=efcore-6.0) seems that will do what you want. – Karen Payne Mar 14 '22 at 01:17
  • Hello Check this solution here https://stackoverflow.com/questions/42355481/auto-create-database-in-entity-framework-core Good luck – Darkk L Mar 14 '22 at 14:13
  • EnsureCreated will work but it is not compatible with migrations, so make sure you don't want to use migrations before you use it. – Peter Dongan Mar 14 '22 at 14:28

1 Answers1

0

Hello You can add to something like this in your Startup.cs if you using Migrations

public void Configure(IApplicationBuilder app)
    {
         using (var serviceScope = 
         app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
         {
               var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
               context.Database.Migrate();
         }
    }

If you are not using Migrations you can change Migrate(); with EnsureCreated(); for using your DB context

Darkk L
  • 889
  • 1
  • 4
  • 14