Aaah… The good old times. I had to add a bug fix to a project I worked on years ago. This was before ORM’s were mainstream so all data access was done through DataTables and DataReaders. While fixing the bug, I wanted to add an extra test to verify if my solution worked without having to go to the database.
This is actually really easy when using DataTables because you can create them in memory:
private DataTable GetCustomers() | |
{ | |
DataTable table = new DataTable("Customers"); | |
// Create two columns, ID and Name. | |
DataColumn idColumn = table.Columns.Add("ID", typeof(int)); | |
table.Columns.Add("Name", typeof(string)); | |
table.Rows.Add(new object[] { 1, "Mary" }); | |
table.Rows.Add(new object[] { 2, "Andy" }); | |
table.Rows.Add(new object[] { 3, "Peter" }); | |
table.Rows.Add(new object[] { 4, "Russ" }); | |
table.AcceptChanges(); | |
return table; | |
} |
Inside my code I was using an IDataRecord so I used the CreateDataReader() method to get a DataReader object that implements the IDataRecord interface.
I pass the created reader to my method:
var table=GetCustomers(); | |
var reader=table.CreateDataReader(); | |
//Call my custom code that expects an IDataRecord | |
var customer=mapper.Map<Customer>(reader); |
However when executing this code, it failed with the following cryptic message:
System.InvalidOperationException : DataTableReader is invalid for current DataTable 'Customers'.
What was the problem? Before the IDataRecord interface inside the DataReader can be used, you should call the Read() function first.
var table=GetCustomers(); | |
var reader=table.CreateDataReader(); | |
//Call the read method to populate the IDataRecord data inside the reader | |
reader.Read(); | |
//Call my custom code that expects an IDataRecord | |
var customer=mapper.Map<Customer>(reader); | |