Wednesday, June 10, 2015

System.InvalidOperationException : DataTableReader is invalid for current DataTable 'Customers'.

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:

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:

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.


bvgheluwe said...

This makes absolutely no sense to me, but it solved the exact same problem I had. On some DataTables, DynamicMap works and with others it throws a MappingException (which disappears when first calling reader.Read()). Very strange.

bvgheluwe said...

Just now I discovered a problem with this approach (which I should have known...): Read() advances the cursor by one position. This means that you always loose the first row in the datatable. The resulting collection thus has one item less than the datatable.