thomasb
thomasb

Reputation: 6035

AutoMapper objects with different property types

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:

I'm realizing that AutoMapper is convention-based, so maybe I should use another tool, but which one exist?

Thanks for your help!

Upvotes: 4

Views: 5516

Answers (1)

severin
severin

Reputation: 5503

.Project() uses Linq to entities, which generates SQL and naturally only understands a very limited set of functions.

If you use

Mapper.Map<IEnumerable<Order>, IEnumerable<OrderDto>>(src) 

your conversions will work fine.

Upvotes: 2

Related Questions