尝试将DataTable转换为POCO列表。在StackOverflow上找到了该主题的一些答案,我认为应该是O.K.但我没有得到正确的结果。结果是一个包含五个项目的空列表。因此,没有从DataRow到POCO对象的映射。 有什么想法可能是错的吗?
AutoMapper是版本6.1.1
AutoMapper.Data版本1.0.0
class Program
{
static void Main( string[] args )
{
var config = new MapperConfiguration( cfg =>
{
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<IDataReader, Person>();
} );
var mapper = config.CreateMapper();
DataTable tbl = DataGenerator.MyPersons();
var result = mapper.Map<List<Person>>( tbl.CreateDataReader() );
}
}
public static class DataGenerator
{
public static DataTable MyPersons()
{
DataTable myPersonssDataTable = new DataTable();
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "FirstName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "LastName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "DateOfBirth",
DataType = typeof( DateTime )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "JobTitle",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "TakenName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "IsAmerican",
DataType = typeof( bool )
} );
myPersonssDataTable.Rows.Add( new object[] { "Lenny", "Belardo", new DateTime( 1971, 3, 24 ), "Pontiff", "Pius XIII", true } );
myPersonssDataTable.Rows.Add( new object[] { "Angelo", "Voiello", new DateTime( 1952, 11, 18 ), "Cardinal Secretary of State", "", false } );
myPersonssDataTable.Rows.Add( new object[] { "Michael", "Spencer", new DateTime( 1942, 5, 12 ), "Archbishop of New York", "", true } );
myPersonssDataTable.Rows.Add( new object[] { "Sofia", "(Unknown)", new DateTime( 1974, 7, 2 ), "Director of Marketing", "", false } );
myPersonssDataTable.Rows.Add( new object[] { "Bernardo", "Gutierrez", new DateTime( 1966, 9, 16 ), "Master of Ceremonies", "", false } );
return myPersonssDataTable;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string JobTitle { get; set; }
public string TakenName { get; set; }
public bool IsAmerican { get; set; }
}
答案 0 :(得分:2)
您忘记添加DataReader映射。
cfg.AddDataReaderMapping();
然后您的代码应该类似于:
...
var config = new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<IDataReader, Person>();
});
...
我希望它有所帮助。