How to clone a DB record from an SqlDataReader instance?

  • Thread starter Thread starter Tin Gherdanarra
  • Start date Start date
T

Tin Gherdanarra

I understand that an SqlDataReader instance acts
as a cursor to a set of query results. This works
fine:

while(readerInstance.Read())
{
Console.WriteLine("{0} {1} {2}", readerInstance[0],
readerInstance[1],
readerInstance[2]);
}

However, what if I want to keep certains records?

An obvious solution is to create my own class or structure
for storing the values and a function to move the items
from the reader to a class/struct instance manually:

private MyPersonClass ClonePersonRecord(SqlDataReader sdr)
{
MyPersonClass retval = new MyPersonClass();
retval.ID = sdr[0];
retval.FirstName = sdr[1];
retval.SurName = sdr[2];
return retval;
}

However, this is a lot of work. I can't believe there is no
wrapper for this, but so far, my search has been futile.
Is it really the visual studio 2005-way to clone a record
manually?
 
Tin,

I would create a typed data set based on the results of the query.

Then, I would write a generic routine that is passed a DataTable and a
DataReader. It would cycle through the columns on the DataTable, and get
the values from the DataReader based on the name/ordinal of the column.

Then, you can pass your typed data table to the routine, as well as the
DataReader, and then it will add a new row, and populate the values.

Hope this helps.
 
Back
Top