ExecuteReader requires an open and available Connection. The connection's current state is Connecting

前端 未结 2 1271
情话喂你
情话喂你 2020-11-21 22:38

When attempting to connect to MSSQL database via ASP.NET online, I will get the following when two or more people connect simultaneously:

ExecuteReade

2条回答
  •  孤街浪徒
    2020-11-21 23:10

    I caught this error a few days ago.

    IN my case it was because I was using a Transaction on a Singleton.

    .Net does not work well with Singleton as stated above.

    My solution was this:

    public class DbHelper : DbHelperCore
    {
        public DbHelper()
        {
            Connection = null;
            Transaction = null;
        }
    
        public static DbHelper instance
        {
            get
            {
                if (HttpContext.Current is null)
                    return new DbHelper();
                else if (HttpContext.Current.Items["dbh"] == null)
                    HttpContext.Current.Items["dbh"] = new DbHelper();
    
                return (DbHelper)HttpContext.Current.Items["dbh"];
            }
        }
    
        public override void BeginTransaction()
        {
            Connection = new SqlConnection(Entity.Connection.getCon);
            if (Connection.State == System.Data.ConnectionState.Closed)
                Connection.Open();
            Transaction = Connection.BeginTransaction();
        }
    }
    

    I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

提交回复
热议问题