【问题标题】:Generic mapping with Automapper to SQLite returns empty list使用 Automapper 到 SQLite 的通用映射返回空列表
【发布时间】:2019-11-28 13:41:20
【问题描述】:

我想创建一个通用数据提供程序函数,它从读取的 SQLite 数据返回 IEnumerable。

创建了 AutoMapper 初始化:

 cfg.CreateMap<IDataRecord, Layout>()

然后调用 CompileMappings() 并在命令本身中读取器返回数据,但映射器无法映射它。 试图为每个字段定义 .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;
            }
        }

使用 Object -> 布局内部异常获取 Unmapped... 异常。

不确定我遗漏了什么,但由于数据在那里,读者可以得到它,但映射器没有映射它。

【问题讨论】:

标签: sqlite automapper idatareader


【解决方案1】:

我觉得方法不好,最后用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();
   }
}

再次感谢蒂姆·科里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多