Jeff
Jeff

Reputation: 36583

AutoMapper Declared Type Map

I'd like to use AutoMapper to implement a "declared type" mapping (generically - that is, I don't want to manually configure this for each type)

So, if I have:

public class Animal 
{ 
   int NumberOfLegs { get; set; }
}

public class Cat : Animal
{ 
   string FurColor { get; set; }
}

And I have an instance of Cat that I want to map to Animal...I want to end up with an Animal instance, not a Cat. I want the same semantics to apply to the rest of the object graph as well (with related entities and collections of entities).

Cats and dogs aside...basically, I have subclasses of DataContracts (that are not DataContracts themselves) that I want to put back into instances of the DataContracts.

Any suggestions on how to do this?

Thanks!

Upvotes: 1

Views: 363

Answers (1)

PatrickSteele
PatrickSteele

Reputation: 14697

Sounds kind of like you want to upcast back to the base class, but you don't want simply a reference, but an instance of your base class. If you wanted to do this generically, I guess you could use some reflection to get all subclasses of Animal and map that type back to Animal. Something like this:

var currentAssem = Assembly.GetExecutingAssembly();
var animals = currentAssem.GetTypes().Where(t => t.IsSubclassOf(typeof(Animal)));
foreach(var animalType in animals)
{
    Mapper.CreateMap(animalType, typeof (Animal));
}

Now you can map any animal subclass back to Animal:

var cat = new Cat { NumberOfLegs = 4, FurColor = "blue" };
var dog = new Dog { NumberOfLegs = 4, WoofType = "squeek" };

var animal1 = Mapper.Map<Cat, Animal>(cat);
var animal2 = Mapper.Map<Dog, Animal>(dog);

Upvotes: 1

Related Questions