1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! this works. I've taken the extra mapping option route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.