开发者

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

开发者 https://www.devze.com 2022-12-16 14:38 出处:网络
I have a method (\"GetDataReader,\" let\'s call it) that returns a SqlDataReader.It\'s inside a Singleton DataFactory class that m开发者_Go百科aintains a persistent connection to the database.

I have a method ("GetDataReader," let's call it) that returns a SqlDataReader. It's inside a Singleton DataFactory class that m开发者_Go百科aintains 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.


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.


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


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.


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


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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消