asp.netasp.net-coremysql-connector

MySqlClient exception: There is already an open DataReader associated with this Connection


am trying to retrieve data from MySql database from a controller in ASP.NET , the main class is registered as singleton wich contains methods that get called from the main controller that either retrieve or insert data into the database, now am making sure to wrap each datareader into a "using" statement, everything seems to work fine...but when i stress test (and that sometimes is as simply as 3 users connected simultaniously ) i get weird and inconsistante MySql errors mainly:

There is already an open DataReader associated with this Connection.

i also tried:


Solution

  • If I were you I would not register the main class as a Singleton where you have the methods that call the database. When registering a class as a Singleton, means that only one instance can be created for that class when the application starts. So when you are stress testing with three users it´s potentinally going to cause problems as there is only one instance for you main class.

    I would suggest to register your mysql database like the following in your startup class:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<MySqlConnection>(_ => new 
            MySqlConnection(Configuration["ConnectionStrings:Default"])); //Your connectionstring here
    }
    

    With the above registered you can access the your MySql database in the controller with Dependency Injection and call it in your controller Action:

    private readonly MySqlConnection _db;
    
    public CheckoutController(MySqlConnection db)
    {
        _db = db;
    }
    
    public ActionResult Index()
    {
        var data = _db.data.ToList();
    
        return View(data);
    }
    

    Here is a link I found for the MySqlConnector to .Net Core: https://mysqlconnector.net/tutorials/connect-to-mysql/