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:

  • 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 get Unable to create a map expression from System.String to System.Int32 errors.
  • Using custom converters for my class, but I always get empty values from ResolutionContext.SourceValues at 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!


    .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.

    链接地址: http://www.djcxy.com/p/37428.html

    上一篇: IEnumerable和嵌套集合

    下一篇: 具有不同属性类型的AutoMapper对象