问题
Trying to convert a DataTable to a POCO list. Found some answers to that topic at StackOverflow and I thougth everything should be O.K. but I doesn't get the correct result. The result is an empty list of five items. So there is no mapping from the DataRow to the POCO object. Any thoughts what can be wrong?
AutoMapper is version 6.1.1
AutoMapper.Data version 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; }
}
回答1:
You forgot to add the DataReader mapping.
cfg.AddDataReaderMapping();
Then your code should look similar to:
...
var config = new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<IDataReader, Person>();
});
...
I hope it helps.
来源:https://stackoverflow.com/questions/46622192/automapper-map-datatable-to-poco-list