How can I "detach" a SqlDataReader from its SqlConnection object?
Asked Answered
G

5

7

I have a method ("GetDataReader," let's call it) that returns a SqlDataReader. It's inside a Singleton DataFactory class that maintains a persistent connection to the database.

The problem with this is that after being returned, the DataReader is still "connected" to the Connection object in my DataFactory. So, I have to make sure the code that calls GetDataReader then calls Close() on the DataReader that comes back, otherwise, it "locks" the Connection with this:

There is already an open DataReader associated with this Command which must be closed first.

How can I "detach" the DataReader before I send it back from GetDataReader? Either that, or clone it and send back the clone? I don't want to have to make the calling code always explicitly close it.

There has to be a best practice here.

Update:

Thanks everyone for your input. The bottom line is that I need to lose the habit of using DataReaders and switch to DataTables. They're much more manageable.

Also, thanks for the note on connection pooling. I knew about it, but just didn't put two and two together and realize I was re-inventing the wheel.

Gardening answered 18/1, 2010 at 15:22 Comment(1)
I have got to stop using DataReaders...Gardening
C
7

DataReader's must stay connected to the db until you no longer need them - that's the nature of using a DataReader so you can't "disconnect" them as such. When you're finished with a data reader, you should close it (.Close()) but then you can't use it any more.

From .NET 2.0 on, if you're using SQL 2005 or later, you can make use of MARS (Multiple Active Result Sets) as explained here. This allows you to use a single connection for multiple data readers and just involves a change to your connection string. However, SqlDataReaders aren't ideal for passing around your code in the way it sounds like you want.

Alternatively (which is what I think you need to do), you may want to use a disconnected resultset which is where DataSet/DataTables come in. You use an SqlDataAdapter to fill a DataSet/DataTable with all the results of a query. You can then use the connection for any other purpose, or close the connection, and it doesn't affect your in-memory resultset. You can pass your resultset around your code without needing to maintain an open database connection.

Comedo answered 18/1, 2010 at 15:31 Comment(1)
Yes, DataTables are a better approach here. I need to stop using DataReaders. I've run into this problem before -- hopefully, I'll learn my lesson this time. Thanks.Gardening
R
2

Do not persist you database connection. There is a feature called "connection pooling". Getting a fresh connection is not expensive.

Reduced answered 18/1, 2010 at 15:30 Comment(0)
R
1

Generally, best practice would be to use connection pooling rather than a persistent connection, to allow simultaneous access by multiple users. The only way I can think of to do what you want to do would be to load a DataSet from the reader and return that.

Rademacher answered 18/1, 2010 at 15:30 Comment(0)
M
1

I think you might be getting your datasets (disconnected embedded data) and datareaders (no data) mixed up. A DataReader without a SqlCnnection is... ummm... just a Reader, i.e. no data ;-)

I think your problem is further up your line of thinking. I'm guessing you're an old school programmer used to doing everything by hand. In the "managed" world of dot net, many things are managed for you; ADO.NET has an effective data connection pooling system already, you shouldn't need to maintain your own pool.

-Oisin

Martini answered 18/1, 2010 at 15:30 Comment(0)
L
0

Here's a handy helper method to execute some SQL against a connection, and have it disconnected from the server:

public static DbDataReader ExecuteReaderClient(DbConnection connection, DbTransaction transaction, String commandText)
{
    DbCommand command = connection.CreateCommand();
    command.CommandText = commandText;
    if (transaction != null)
        command.Transaction = transaction;

    DbDataAdapter adapter = DbProviderFactories.GetFactory(connection).CreateDataAdapter();

    adapter.SelectCommand = command;
    DataSet dataset = new DataSet();

    try
    {
        adapter.Fill(dataset);
    }
    catch (Exception e)
    {
        throw new Exception(
                  e.Message + "\r\n" +
                  "Command Text" + "\r\n" +
                  commandText, e);
    }

    try
    {
        return dataset.CreateDataReader();
    }
    finally
    {
        dataset.Dispose();
    }
}
Lees answered 23/11, 2017 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.