ozz
ozz

Reputation: 5366

Automapper unexpected behaviour with map between inherited types

I have the following situation (C#):

public class A: B
{
      public ComplexType MyCT {get;set;}

}

public class B: 
{
      public string MyString {get;set;}

}

I have an instance of A and I want to use Automapper to map it to an instance of B as after the mapping I do not need "MyCT" (this is a cut down version obviously).

B myB = Mapper.Map<A, B>(myA);

but when I try to do something with myB (I'm saving it into Azure which can't handle my complex type, hence trying to throw it away if you like) an exception is thrown telling my that MyCT is still hanging around the myB object.

When I debug I can cast it to A and sure enough I have access to MyCT.

What am missing, I feel like I'm fundamentally missing something here presumably to do with the inheritance between the two types.

Upvotes: 2

Views: 570

Answers (2)

Pero P.
Pero P.

Reputation: 26992

It looks like you have not defined a mapping for the two types which is simply:

Mapper.CreateMap<A, B>();

(If you take a look at the Getting Started guide it gives some hints on how you can centralize these mapping configurations in one place on application startup.)

It looks like that without the mapping between the two types having been defined, Automapper is falling back to an upcast of your A instance to the B type. You actually want to achieve a flattening which Automapper can only do if it knows about the mapping between the two types explicitly.

Here's a code sample that illustrates this:

using System;
using AutoMapper;

class Program
{
    static void Main(string[] args)
    {
        B b = Mapper.Map<A, B>(new A());
        Console.WriteLine(b.GetType()); //A

        Mapper.CreateMap<A, B>();       //define the mapping
        b = Mapper.Map<A, B>(new A());
        Console.WriteLine(b.GetType()); //B

        Console.ReadLine();
    }
}

public class A: B
{
}

public class B
{
}

Upvotes: 2

sean woodward
sean woodward

Reputation: 1783

Add Mapper.CreateMap<A, B>().

Upvotes: 1

Related Questions