Question

I have an object below:

public class DatabaseAccess
{
    private static string sConnStr;
    private static SqlConnection sqlConn;

    private static string ConnectionString
    {
        get
        {
            if (String.IsNullOrEmpty(sConnStr))
            {
                sConnStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            }
            return sConnStr;
        }
    }

    public static int OpenConnection
    {
        get
        {
            sqlConn = new SqlConnection(ConnectionString);
            return 0;
        }
    }

    public static SqlConnection Connection
    {
        get
        {
            if (sqlConn.State != ConnectionState.Open)
            {
                sqlConn = new SqlConnection(ConnectionString);
                sqlConn.Open();
            }
            return sqlConn;
        }
    }
}

So whenever I need a connection in my web application, I use something like:

DataTable dt = new DataTable();
using (SqlConnection cnn = DatabaseAccess.Connection)
{
    using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
    {
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.Fill(dt);
    }
}

return dt;

It all seems well except when there are 2 users running the codes at the same time, I will get in my web application the following error:

There is already an open DataReader associated with this Command needs to be Closed.

I need some advice how do I resolve the above issue?

Thank you.

Was it helpful?

Solution

That's because you're sharing connection objects - don't do that. DatabaseAccess.Connection should create a new SqlConnection every time.

OTHER TIPS

Try to create a new instance of SqlConnection in the using statement

DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    cnn.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
    {
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.Fill(dt);
    }
}

return dt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top