I\'m writing a specific kind of object-mapper. Basically I want to convert from a DataTable
that has the fields a
, b
and c
Sometimes a 3rd party library is the easiest way to do it, AutoMapper will do exactly what you want with just a few lines of code
//This just needs to be run once, maybe in a static constructor somewhere.
Mapper.CreateMap();
//This line does your mapping.
List myBusinessObject =
Mapper.Map>(myDataTable.CreateDataReader());
If your source data does not exactly match your business object all you need to do is add some setup info to CreateMap
.
class MyBusinessObject
{
public int Answer;
public string Question { get; set; }
}
//In some static constructor somewhere, this maps "a" to "Answer" and "b" to "Question".
Mapper.CreateMap()
.ForMember(dto => dto.Answer, opt => opt.MapFrom(rdr => rdr["a"]))
.ForMember(dto => dto.Question, opt => opt.MapFrom(rdr => rdr["b"]));