I have mvc 4 website with DataHelperClass below to execute query. My problem is sometimes, website through exeception as title. I used using block to dispose SqlCommand and SqlDataAdapter but not success.
Please help me, sorry for my english.
        try
        {
            if (_conn.State == ConnectionState.Closed)
                _conn.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, _conn))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                    sqlCommand.Parameters.AddRange(parameters);
                //// check transaction is exist
                if (_trans != null)
                    sqlCommand.Transaction = _trans;
                DataTable dt = new DataTable();
                using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(dt);
                }
                return dt;
            }
        }
        finally
        {
            //// close connection automatically if transaction is not exist
            if (_trans == null) { _conn.Close(); }
        }
                It may be caused that your connection is not really opened, because when this code is called:
if (_conn.State == ConnectionState.Closed)
      _conn.Open();
Connection state could be: Broken, or Connecting or Fetching (See all enum list). 
This may happen if you try to share your connection between many threads. I think you need to create a new connection each time this method is called. You can find many examples how to do it, including MSDN.
EDIT:
There is a great answer for such a question: ExecuteReader requires an open and available Connection. The connection's current state is Connecting
But if you really-really need it, try to prevent using the same connection with two or more threads by using lock (it is wrong actually, see the link above):
lock(_conn)
{
    DataTable dt = new DataTable();
    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
    {
        sqlDataAdapter.Fill(dt);
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With