using (IDataReader dr = DatabaseContext.ExecuteReader(command))
{
if (dr.Read())
{
AutoMapper.Mapper.CreateMap<IDataReader, ProductModel>();
return AutoMapper.Mapper.Map<IDataReader, IList<ProductModel>>(dr);
}
return null;
}
如果dr只有一行 -> error: 抛出类型为'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'的异常
如果dr有多于一行,则运行ok。
帮忙吗?
问题是Automapper也在调用Read() -因此总是试图查看第二条记录。如果你想一下,如果阅读器中有1000行- AutoMapper如何将其转换为列表而不遍历它们并调用Read()?
将行改为调用HasRows
。
using (IDataReader dr = DatabaseContext.ExecuteReader(command))
{
if (dr.HasRows)
{
AutoMapper.Mapper.CreateMap<IDataReader, ProductModel>();
return AutoMapper.Mapper.Map<IDataReader, IList<ProductModel>>(dr);
}
return null;
}
添加AutoMapper。Net4并在CreateMap之前添加映射器,如下所示:
MapperRegistry.Mappers.Add(new DataReaderMapper());
MapperRegistry.Mappers.Add(new NameValueCollectionMapper());
MapperRegistry.Mappers.Add(new HashSetMapper());
MapperRegistry.Mappers.Add(new ListSourceMapper());
MapperRegistry.Mappers.Add(new TypeConverterMapper());