Search code examples
c#mariadbmariadb-connector

MySqlConnection.Open() System.InvalidCastException: Object cannot be cast from DBNull to other types


I have simple connectionstring to MySql (MariaDB 5.5.5-10.11.0) written in c#:

MySqlConnection Database = new MySqlConnection("Server=127.0.0.1; Port=3306; Database=test; Uid=user; Pwd=MyPassword; Ssl Mode=Required; convert zero datetime=True;");

Everything works fine on two computers (Windows 10 and Windows 11). But when I try to launch this app on Windows Server 2022 I get this error:

System.InvalidCastException: Object cannot be cast from DBNull to other types.
   at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider)
   at System.Convert.ToInt32(Object value, IFormatProvider provider)
   at MySql.Data.MySqlClient.Driver.LoadCharacterSets(MySqlConnection connection)
   at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection)
   at MySql.Data.MySqlClient.MySqlConnection.Open()
   at MariaDB.Program.StartAPI()

Error is thrown on Database.Open();

MariaDB is installed and running, Ssl is working, user's pemissions are granted, port is correct. Any ideas please?

Whole program:

using System;
using MySql.Data.MySqlClient;

namespace MariaDB
{
    internal class Program
    {
        MySqlConnection Database = new MySqlConnection("Server=127.0.0.1; Port=3306; Database=test; Uid=user; Pwd=MyPassword; Ssl Mode=Required; convert zero datetime=True;");

        static void Main(string[] args)
        {
            Program p = new Program();
            p.OpenDB();
        }

        private void OpenDB()
        {
            Database.Open();
            Console.WriteLine("Ok");
            Console.ReadLine();
        }
    }
}

Solution

  • The same thing happened to me. Change MySql.Data.MySqlClient to MySqlConnector and the problem was solved

    The database I use is already in production so it was easier for me to change the connector instead of downgrading my database

    I detail a little what I did:

    • My project was working on Visual Studio 2017 with .NET Core 2.1. I had to update to Visual Studio 2022 and change the .NET Core to version 3.1
    • In NuGet package manager uninstall MySql.Data and install MySqlConnector version 2.2.2
    • Follow the recommendations of the official page MySqlConnector