Home > other >  Storing connection string as named secret with Pomelo.EntityFramework.MySql
Storing connection string as named secret with Pomelo.EntityFramework.MySql

Time:07-25

I'm trying to set up an ASP .NET Core project with Entity Framework Core with a MySQL database that already has some tables in it. I'm using the Pomelo.EntityFramework.MySql package to connect to the database. Passing the connection string as a user-secret doesn't work.

I've set my connection string in user-secrets to ConnectionStrings:Smokey = server=localhost;user=asp;password=password;database=data and then I run dotnet ef dbcontext scaffold Name=ConnectionStrings:Smokey "Pomelo.EntityFrameworkCore.MySql"

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySql("name=ConnectionStrings:Smokey", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.29-mysql"));
        }
    }

Running this yields System.ArgumentException: Option 'name' not supported. at MySqlConnector.MySqlConnectionStringOption.GetOptionForKey(String key) in /_/src/MySqlConnector/MySqlConnectionStringBuilder.cs:line 940

It works if I run it with the connection string directly in the source code.

How can I store the connection string/credentials separately from the codebase with EF Core MySQL?

CodePudding user response:

This is a bug in Pomelo.EntityFrameworkCore.MySql that was fixed in 6.0.2.

(As of the time of writing, I don't see 6.0.2 as an available version on NuGet but I would expect it to be uploaded soon.)

CodePudding user response:

I fixed it you don't even need to override OnConfiguring at all that was just something ef scaffold generated.

You can pass in a connection string during configuration like

services.AddDbContext<DataContext>(
        dbContextOptions => dbContextOptions
            .UseMySql(connectionString, serverVersion)

You can use the IConfiguration object here to access user-secrets

var connectionString = new MySqlConnector.MySqlConnectionStringBuilder()
    {
        Server = "localhost",
        UserID = configuration["MySQLUser"],
        Password = configuration["MySQLPass"],
        Database = "data"
    }.ToString();
  • Related