Best method for Populating DataSet from a SQLDataReader

30,850

Solution 1

Try DataSet.Load(). It has several overloads taking an IDataReader.

Solution 2

DataTable.load() can be used for a generic approach.

do {
    var table = new DataTable();
    table.Load(reader);
    dataset.Tables.Add(table);
} while(!reader.IsClosed);
Share:
30,850
Andrew Harry
Author by

Andrew Harry

I have been a web developer for the nearly n years. I have a background in graphic design and programming. I program in C# and VB. I can handle most DBA tasks. I prefer ASP.net MVC Personal blog

Updated on August 13, 2022

Comments

  • Andrew Harry
    Andrew Harry over 1 year

    I am working on a DAL that is getting a DataReader Asynchronously.

    I would like to write a single method for transforming the DataReader into a DataSet. It needs to handle different schema so that this one method will handle all of my fetch needs.

    P.S. I am populating the SQLDataReader Asynchronously, please don't give answers that are getting rid of the DataReader.

  • Andrew Harry
    Andrew Harry about 15 years
    Ended up using a DataTable (which has the same method)
  • KolA
    KolA almost 9 years
    it needs string[] or DataTable[] as third parameter. Is there any way to populate initially empty DataSet with no tables without knowing its schema beforehand? It also looks like this solution is partially blocking as DataSet.Load() won't take advantage of ReadAsync() and NextResultAsync() methods of SqlDataReader
  • mcNux
    mcNux almost 8 years
    This is the answer to the question asked. Thanks.