Michiel Vlootman
Michiel Vlootman

Reputation: 85

AutoMapper mapping nested propery of object-type

When I use AutoMapper to map an object from a namespace to another namespace (with same datatypes) it seems to map to the wrong namespace.

Simple sample:

namespace AutoMapperSamples.Namespace10
{
  public class Outer
  {
    public int Value { get; set; }
    public object Inner { get; set; }
  }
}  

namespace AutoMapperSamples.Namespace20
{
  public class Outer
  {
    public int Value { get; set; }
    public object Inner { get; set; }
  }
}

Mapping this like:

var dest = config.CreateMapper().Map<Namespace10.Outer, Namespace20.Outer>(source);

Results in Outer class mapped correctly to Namespace20.Outer but the Inner object is of type Namespace10.Inner (instead of if Namespace20). Since this my classes are generated from a webservice (svcUtil) (where the field is a choice type (which can be one of two classes) thus created as an object type.

Is there a convenient way around this?

Upvotes: 1

Views: 302

Answers (1)

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

It because mapping configuration has no custom rule to map object to object. Possible workaround is to add AfterMap action and map Inner property manually:

public MapperConfiguration Config { get; set; }

[SetUp]
public void SetUp()
{
    var innerConfig = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Namespace10.Inner, Namespace20.Inner>();
    });

    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Namespace10.Outer, Namespace20.Outer>()
        .AfterMap((src, dest) =>
        {
            dest.Inner = innerConfig.CreateMapper().Map<Namespace20.Inner>(src.Inner as Namespace10.Inner);
        });
    });

    Config = config;
}

[Test]
public void Map()
{
    Namespace10.Outer source = new Namespace10.Outer();
    source.Inner = new Namespace10.Inner();
    var dest = Config.CreateMapper().Map<Namespace10.Outer, Namespace20.Outer>(source);

    Assert.AreEqual(typeof(Namespace20.Inner).FullName, dest.Inner.GetType().FullName);
}

You may use Custom value resolver instead.

Upvotes: 1

Related Questions