sqliteautomapperidatareader

Generic mapping with Automapper to SQLite returns empty list


I'd like to create a generic data provider function which returns IEnumerable from the SQLite data read.

Created the AutoMapper init:

 cfg.CreateMap<IDataRecord, Layout>()

Then called the CompileMappings() and in the command itself the reader returns the data, but the mapper fails to map it. Tried to define for every field the .ForMember()... same error.

  public static IEnumerable<T> ExecuteReaderCommand<T>(SQLiteConnection connection, SQLiteCommand command)
        {
            using (var scope = new TransactionScope())
            {
                var result = Enumerable.Empty<T>();

                try
                {
                    connection.Open();
                    command.Connection = connection;

                    var reader = command.ExecuteReader();

                    result = Mapper.Map<IDataReader, IEnumerable<T>>(reader);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, "Can't execute {command}, with {connection}", command, connection);
                    return result;
                }
                finally
                {
                    connection.Close();
                }

                scope.Complete();
                return result;
            }
        }

Getting the Unmapped... exception with Object -> Layout inner exception.

Not sure what am I missing, but since the data is there, the reader gets it but the mapper not mapping it.


Solution

  • I think the approach was not good, and finally solved the problem with Dapper. Great tool recommending it. This way all the mappings done correctly, without Automapper.

    public IEnumerable<T> QueryData<T, U>(string sqlCommand, U parameters, string connection)
    {
       using (var conn = new SQLiteConnection(connection))
       {
          return conn.Query<T>(sqlCommand, parameters).AsEnumerable();
       }
    }
    

    Thanks again Tim Corey