Home  >  Q&A  >  body text

C# - Entity Framework Core - Automated database generation

<p>When I run my desktop application for the first time, I want the database and table structure to be created automatically. </p><p> I can't find any examples or documentation on the equivalent method in EFCore. </p><p> I did everything as described in this document: https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-example.html </p><p> But I still have the problem: Exception: 'Microsoft.Data.SqlClient.SqlException' thrown in Microsoft.Data.SqlClient.dll and the database is empty :( If you can help me please let me know. </p><p></p> <pre class="brush:php;toolbar:false;">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("Unable to connect to the server, please contact the administrator"); break; case 1045: MessageBox.Show("Invalid username/password, please try again"); break; } }; }</pre></p>
P粉520204081P粉520204081420 days ago416

reply all(1)I'll reply

  • P粉986028039

    P粉9860280392023-08-27 16:17:15

    Hello, if you use migrations, you can add something similar to the following in your Startup.cs:

    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 replace Migrate(); with EnsureCreated(); to use your database context.

    reply
    0
  • Cancelreply