I want to map my Entity Framework entities (generated from a legacy database) to custom DTO objects (which should be nice and clean).
My legacy DB has entities looking a bit like this:
internal class Order {
int id;
string Shipping_date;
string quantity;
}
And I want to map it to a nicer DTO object:
public class OrderDto {
int id;
DateTime? ShippingDate;
int Quantity;
}
I have written an "entity container" to provide dependency injection, which returns values this way:
public IEnumerable<OrderDto> GetPaginatedOrders(int page, int pageSize)
{
return this.db.Orders
.OrderByDescending(c => c.id)
.Paginate(page, pageSize)
.Project()
.To<OrderDto>()
.AsEnumerable();
}
So: change of types, and change of property names.
Were it only change of property names, it would be easy-but-tedious:
Mapper.CreateMap<Order, OrderDto>()
.ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.quantity))
.ForMember(dest => dest.ShippingDate, opt => opt.MapFrom(src => src.Shipping_date));
This is not enough with type changes. I tried a whole bunch of stuff:
- Parsing the properties at the mapping declaration, like
src => int.Parse(src.quantity)but Linq doesn't like it. - Extending the EF entities with custom properties like
QuantityInt { get { return int.Parse(this.quantity) } }and using these in the mapping, but AutoMapper doesn't like it, and explicitly don't support them. - Mapping system types one to another like
Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32)but I still getUnable to create a map expression from System.String to System.Int32errors. - Using custom converters for my class, but I always get empty values from
ResolutionContext.SourceValuesat run-time from my entities (I'm guessing that they are disposed before AutoMapper gets them or something like this).
I'm realizing that AutoMapper is convention-based, so maybe I should use another tool, but which one exist?
Thanks for your help!
Mapper.Map<T>(...)to map your queries or are you doing.Project().To<T>()from the Queryable Extensions namespace underAutomapper.QueryableExtensions? - Scott Chamberlain