Automapper无法正确映射IDataReader到字符串

时间:2017-05-22 11:28:05

标签: automapper idatareader

我正在使用automapper来映射IDataReader。只要我使用它从IDataReader映射到DTOs就没有问题,但在我为string添加映射后,它无法按预期工作。看看我编写的以下示例代码来演示问题:

static void Main(string[] args)
{
    var configuration = new MapperConfiguration(cfg =>
    {
        //Here Group is one of my DTOs
        cfg.CreateMap<IDataReader, Group>()
            .ForMember(dest => dest.Id, options => options.MapFrom(src => src["Id"]))
            .ForMember(dest => dest.Name, options => options.MapFrom(src => src["Name"]));

        //This is the mapping for string type, if I remove it the outcome will not change, 
        //it seems automapper does not even see this mapping
        cfg.CreateMap<IDataReader, string>()
            .ConvertUsing(src => src.GetString(0));

    });
    var mapper = configuration.CreateMapper();

    using (SqlConnection connection = new SqlConnection("Data Source=MICHAEL-PC;Initial Catalog=RollingStonesDB;User ID=admin;Password=admin"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("GetSaltByLogin 'jt'", connection))
        using (IDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                //here instead of giving me the expected result it gives me "System.Data.SqlClient.SqlDataReader"
                string value = mapper.Map<string>(reader);
            }
        }
    }
}

在这一行string value = mapper.Map<string>(reader);中,我希望得到string中第一列的实际IDataReader值,而不是"System.Data.SqlClient.SqlDataReader"。现在真正奇怪的是,当我从上面的代码中删除此行.ForMember(dest => dest.Name, options => options.MapFrom(src => src["Name"]));时,映射将按预期工作。对我来说,好像这是一个错误。如何优雅地解决此问题,以便为DTOsstring制作映射?

0 个答案:

没有答案