Updated AutoMapper from 3 to 4 broke inheritance mapping

心已入冬 提交于 2019-12-10 15:23:03

问题


I updated AutoMapper from 3.3.1 to 4.0.4 which broke the following mapping with this message

Unable to cast object of type 'Foo' to type 'BarDTO'

Classes

public class FooDTO
{
    // omitted
}

// derived DTO
public class BarDTO : FooDTO
{
    public string Extra { get; set; }
}

Mapping config

Mapper.CreateMap<Foo, FooDTO>().ReverseMap();
Mapper.CreateMap<Foo, BarDTO>();

Mapping

Map<Foo, BarDTO>(foo); // throws cast exception

I also tried using the .Include() method, but didn't make a difference.

Mapper.CreateMap<Foo, FooDTO>()
      .Include<Foo, BarDTO>()
      .ReverseMap();
Mapper.CreateMap<Foo, BarDTO>();

Am I doing something wrong, or is it a bug?


回答1:


This is a known change happened from 3.x.x to 4. Configuring the mapping inside Mapper.Initialize would solve the problem.

e.g. In 3.x.x mapping is done like this:

Mapper.CreateMap<Order, OrderDto>()
            .Include<OnlineOrder, OnlineOrderDto>()
            .Include<MailOrder, MailOrderDto>();
        Mapper.CreateMap<OnlineOrder, OnlineOrderDto>();
        Mapper.CreateMap<MailOrder, MailOrderDto>();

Now, In 4.x.x mapping should be done in Initialize method using delegate.

Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Order, OrderDto>()
                .Include<OnlineOrder, OnlineOrderDto>()
                .Include<MailOrder, MailOrderDto>();
            cfg.CreateMap<OnlineOrder, OnlineOrderDto>();
            cfg.CreateMap<MailOrder, MailOrderDto>();
        });

Here's the discussion related to the issue .

Update ver: bug fixed for 4.1.0 milestone

Alternatively, you can do is seal the mappings.

Mapper.Configuration.Seal();


来源:https://stackoverflow.com/questions/32141447/updated-automapper-from-3-to-4-broke-inheritance-mapping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!