Customize DB connection string in code

March 15th 2024 MySQL EF Core .NET

In my recent dealings with MySQL, I learned that some connection string options affect the behavior to such an extent that the code will break unless they are set correctly. For example, I had to set the correct GUID format and enable support for loading local data. To prevent the application failing because somebody configured the connection string wrong, you can make sure in code that the selected options are set correctly.

And you don't need to parse and modify the connection string directly. You can use the MySqlConnectionStringBuilder class instead and do it in a strongly typed manner:

var builder = new MySqlConnectionStringBuilder(connectionString)
{
    GuidFormat = MySqlGuidFormat.Binary16,
    AllowLoadLocalInfile = true
};
connectionString = builder.ConnectionString;

Just use this code to process the connection string from your configuration before passing it on to the database provider.

It's perfectly possible that the configured connection string already contains the said option (set correctly or incorrectly). This code will correctly recognize all the supported spellings for each option, and make sure that the option will only appear once in the final connection string and be set correctly.

You can find code for a small sample with a couple of tests in my GitHub repository. You can easily try it out with additional input connection strings to make sure it would correctly handle even your case.

When your application depends on external configuration, it's a good idea to validate or even fix the configured values when possible. In this particular case, I'm doing it with a database connection string. By processing the connection string in code before using it, I don't need to document the options required for the application to work. Not do I have to rely on the person configuring it to read that documentation and not make a mistake.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License