简体   繁体   中英

New version of Automapper throws cast exception when subtype mapping is defined

Suppose I have a source class and two destination classes, one more general and one more specific (which inherits from the more general one):

public class Source
{   
    public int A { get; set; }
    public string Str { get; set; }
}

public class DestinationBase
{
    public int A { get; set; }
}

public class DestinationDerived : DestinationBase       
{
    public string Str { get; set; }
}

For Automapper 3.*, this code worked perfectly:

    Mapper.Initialize(cfg => {
        cfg.CreateMap<Source, DestinationBase>();
        cfg.CreateMap<Source, DestinationDerived>()
            .IncludeBase<Source, DestinationBase>();
    });

    var src = new Source() { A = 1, Str = "foo" };
    var dest = new DestinationBase();

    Mapper.Map(src, dest);

However, after upgrading to 4.0.4, this mapping throws exception:

System.InvalidCastException: Unable to cast object of type 'DestinationBase' to type 'DestinationDerived'

Is there anything I'm doing wrong or is this a bug in AutoMapper?

The code in .net fiddle:

It would appear that in 4.x you no longer need to explicitly include base. The following works just fine and outputs a as 1 as expected.

Mapper.Initialize(cfg => {
    cfg.CreateMap<Source, DestinationBase>();
    cfg.CreateMap<Source, DestinationDerived>();
});

var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationBase();

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);

Likewise, mapping to DestinationDerived also properly maps properties inherited from base:

var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationDerived();

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM