0

I have an Azure Function app. I have enabled MySQLin App feature. My function is written in C# using EF Core. When attempting to establish a connection using MYSQLCONNSTR_localdb as documented, I get an exception in the logs.

This is my code to create the DBContext:

   public partial class MyContext : DbContext
    {
        public static MyContext Factory(string connectionString)
        {

           //String returned from MYSQLCONNSTR_localdb     
           //Database=localdb;Data Source=127.0.0.1:50249;User Id=azure;Password=****
           var options = new DbContextOptionsBuilder<MyContext >()
                         .UseMySql(builder.ConnectionString)
                         .Options;      

           return new MyContext (options);

        }
    }

When executing the following, I get the following exception: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call.

   using var dbcontext = MyContext.Factory(settings.ConnectionString);
   var result = dbcontext.Database.CanConnect();
jlo-gmail
  • 4,453
  • 3
  • 37
  • 64

1 Answers1

0

The problem is the Connection string provided by Azure is wrong:

Database=localdb;Data Source=127.0.0.1:50249;User Id=azure;Password=****

You cannot correct the format and store the value because the port may change. This is an issue with Azure service that has existed for over 2 years as far as I can tell.

This code corrects the connection string:

var connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb") 

public static MyContext Factory(string connectionString)
{
    {
        //WRONG: Database=localdb;Data Source=127.0.0.1:50249;User Id=azure;Password=****
        //CORRECT: server=127.0.0.1;userid=azure;password=XXXX;database=localdb;Port=nnnnn
        var builder = new System.Data.Common.DbConnectionStringBuilder();
        builder.ConnectionString = connectionString;

        object dataSource;
        if (builder.TryGetValue("Data Source", out dataSource))
        {
            var parts = dataSource.ToString().Split(":");
            builder.Remove("Data Source");
            builder.Add("server", parts[0]);
            builder.Add("Port", parts[1]);
        }

        var options = new DbContextOptionsBuilder<MyContext>()
                    .UseMySql(builder.ConnectionString)
                    .Options;      

        return new MyContext(options);
    }
jlo-gmail
  • 4,453
  • 3
  • 37
  • 64