使用 Automapper 到 SQLite returns 空列表的通用映射

Generic mapping with Automapper to SQLite returns empty list

我想创建一个通用数据提供程序函数,returns IEnumerable 从 SQLite 数据中读取。

创建了 AutoMapper init:

 cfg.CreateMap<IDataRecord, Layout>()

然后调用 CompileMappings() 并在命令本身中 reader returns 数据,但映射器无法映射它。 试图为每个字段定义 .ForMember()... 同样的错误。

  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;
            }
        }

正在获取未映射...异常,对象 -> 布局内部异常。

不确定我错过了什么,但由于数据在那里,reader 得到它但映射器没有映射它。

我觉得方法不好,最后用Dapper解决了问题。推荐它的好工具。 这样所有映射都正确完成,没有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();
   }
}

再次感谢蒂姆·科里