Reader closed error during Parallel ForEach handling automapper

170 Views Asked by At

I get data from a database by using telerik openaccess ORM. I store these in a list by using ToList() method.

Then I use a Parallel.ForEach to map the model objects to DTO objects by using AutoMapper.

An error occurs in the Parallel.ForEach after the first or second treatment in the loop:

DataStoreException: System.InvalidOperationException: Invalid attempt to call IsDBNull when reader is closed.
   at System.Data.SqlClient.SqlDataReader.CheckHeaderIsReady(Int32 columnIndex, Boolean permitAsync, String methodName)
   at System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i)
   at OpenAccessRuntime.Data.IntConverter.Read(DataHolder& data)
   at OpenAccessRuntime.Relational.RelationalGenericOID.CopyKeyFields(DataHolder& data)
   at OpenAccessRuntime.Relational.fetch.FopGetOID.fetch(FetchResult fetchResult, StateContainer stateContainer)
   at OpenAccessRuntime.Relational.fetch.FetchSpec.createRow(FetchResult fetchResult, StateContainer stateContainer)

I can admit the connection is not thread safe but why to need this connection yet after using the ToList() method ? All data are supposed to be retrieved after using this method.

Does it exist another way to do it ?

My code:

IEnumerable<Person> persons = database.GetData<Person>().ToList();

var safeList = new ConcurrentBag<PersonDTO>();
Parallel.ForEach(persons, (p) =>
{
    var dto = Mapper.Map<PersonDTO>(p);
    safeList.Add(dto);
});

return safeList.ToList();
0

There are 0 best solutions below