03 January 2008

Don't use DataReader with ObjectDataSource

I develop a lot of database heavy web apps, and sometimes my business layer returns DataReader objects. Like a good little coder I always use CommandBehavior.CloseConnection, like this...

Return ExecuteReader(CommandBehavior.CloseConnection)

I assumed if I passed this to an ObjectDataSource, then .Net would take care of closing the database connection for me, but this is not the case. Even though I've specified the command behavior, it just leaves the connection open.

The best solution seems to be return a DataSet or DataTable, which means that you can manually close the database connection before passing the object to the ObjectDataSource.

2 comments:

Unknown said...
This comment has been removed by the author.
NickV said...

I'm already going the route you mention; only, I fill a BindingList with strongly typed objects instead of filling a DataTable. I would imagine it'd be faster to pass the DataReader to the GridView... but how to do it safely?

Have you considered closing the datareader in the ObjectDataSource.OnSelected method? I haven't tried it... I worry that an exception would fire and the OnSelected event would never fire. =(