Search code examples
.netdatareader

Example of generic DataReader code (.net)


As my experience with .Net really began as working on existing in-house applications for a company, I feel I've picked up so many bad coding practices without realising it. One that i am desperately trying to move on from is that DataSets are used for everything. (I do get that strongly typed datasets have there place and they certainly have some uses...but not for the majority of cases e.g. selecting data)

I'm building up a "helper" class for generic database work...I've got a method which returns a data table (for selects etc.) and I guess by default (and most examples in books/online) would use the DataAdapter's Fill method but certainly as a performance gain, want to replace this with a data reader that reads all the rows and then closes...which I guess is how the Fill method works underneath...but I'd prefer not to simply go for the lazy way if performance on large result sets is potentially going to impact.

Anyway, I can't for the life of me find an example of a dataReader being used to generically fill a datatable...I'm sure there would be both good and bad examples and therefore an agreed best practice on how to perform such a task. A link (or even a post) to such code would be brilliant! I'm mostly VB.Net but c# is no obstacle.

Note: Sorry if this sounds lazy also, I just figured this sort of example would be posted everywhere...no need to re-invent the wheel etc. thanks!


Solution

  • The reason you can't find an example of a DataReader being used to generically fill a DataTable is because you can do the same thing with the Fill() method in the DataSet, so you would just be reinventing the wheel.

    You're not going to find a performance benefit by populating the DataTable directly with a DataReader.