开发者

AutoMapper unsupported polymorphism?

Assume the following object hierarchy:

class Customer
{
    int Id { get; set; }
    string Name { get; set; }
}

class CustomerStubDTO
{
    int Id { get; set; }   
}

class CustomerDTO : CustomerStubDTO 
{
    string Name { get; set; }
}

class Order
{
    Customer Customer { get; set; }
}

class OrderDTO
{
    CustomerStubDTO Customer { get; set; }
}

And the following mapping:

CreateMap<Order, OrderDTO>();
CreateMap<Customer, CustomerDTO>(); 

This does not work, AutoMapper wants a mapping like the following instead:

CreateMap<Customer, CustomerStubDTO>(); 

But I want OrderDTO.Customer to contain an instance of CustomerDTO instead so I have access to the Name property, among other things.

I was able to use .Include<TSource, TDestination> for this behavior when the source class has other derivees, but not when it is stand alone. (for example, if there was a CustomerStub corresponding to CustomerStubDTO and Customer corresponding to CustomerDTO)

What this means is, that the following does not work either:

CreateMap<Customer, CustomerStu开发者_StackOverflow社区bDTO>().Include<Customer, CustomerDTO>(); 

Any ideas?


I downloaded the source and looked through it and couldn't find this scenario being supported.

I implemented it myself, I guess I'll submit a patch.


Not sure what you are trying to do. The following works as expected once you change the "Customer" on OrderDTO to type "CustomerDTO":

Mapper.CreateMap<Customer, CustomerDTO>();
Mapper.CreateMap<Order, OrderDTO>();
Customer customer = new Customer{Id=1,Name="John"};
Order order = new Order{Customer = customer};
var orderDto = Mapper.Map<Order, OrderDTO>(order);

If you wanted to keep "CustomerStubDTO" on Order you would instead map Customer->CustomerStubDTO then CreateMap<Customer, CustomerStubDTO>(); is the way to go as you noted.

Automapper does not take inheritance into account when creating the TypeMap it uses internally to figure out what to map where. I'm not even sure doing that makes sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜