How do I set the OnConfiguring method in my DbContext without any hardcoded connection string?

asp.net-core c# entity-framework-core

Question

I'm using multiple examples on how to set up my MySql service but in almost every one (including the Microsoft), they are using a hard coded connection string.

This is my startup:

    services.AddDbContext<DbContext>(options =>
    {
        options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
        mysqlOptions =>
        {
            mysqlOptions.ServerVersion(new ServerVersion(new Version(8, 0, 18)));
        });
    });

And whenever I try to Update-Database I see an error telling me that there's no password setted

MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost' (using password: YES).

After looking around a bit I found an overrideable method called OnConfiguring, but I want to set the connection string in a dynamic way, cause If I change my environment, I want that string to change too.

This is where I found almost every example with hardcoded strings (ex. https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html)

1
0
12/30/2019 7:02:33 PM

Popular Answer

Based on the comment, I think you want to separate the EF Core related classes to a different assembly.

In the UseMySql there is an option to configure MigrationsAssembly. You can get more details here

Here is pseudo-code for SQL Server.

services.AddDbContext<EFCoreDemoContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
            assembly => assembly.MigrationsAssembly(typeof(EFCoreDemoContext).Assembly.FullName));
});
0
12/31/2019 3:34:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow