我正在使用automapper
从IDataReader
. 只要我用它来映射 fromIDataReader
到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"]));
从上面的代码中删除这一行时,映射将按预期工作。对我来说,这似乎是一个错误。如何优雅地解决这个问题,以便我将拥有我的DTOs
和的映射string
?