How do I get AutoMapper to map classes whose type isn't known at compile time?

Let's say that I have a class Schedule that contains a property called Event that's a nested class. Let's say that there are many types of events, so the actual value of the property would be some subclass (or descendant) of Event. The event could be a Conference or a ReligiousCeremony or yada yada yada.

Now let's say that all of these classes are in an "old" namespace and I'm using AutoMapper to convert these into updated version in a "new" namespace. (Ideal use case for AutoMapper.) v1.Schedule maps to v2.Schedule and v1.Conference maps to v2.Conference and so on.

The issue I have is that because Schedule.Event isn't of type v1.Conference, AutoMapper isn't identifying it as an object type it can map. Specifically, my class definitions are coming from an XSD and the Schedule.Event property is of type object.

Is there a way to get AutoMapper to inspect the actual type of an object and apply the appropriate mapping?

My current work-around (which another developer is testing right now) is as follows:

var v2Schedule = mapper.Map<v2.Schedule>(v1Schedule);
if (v2Schedule.Event is v1.Conference) { v2Schedule.Event = mapper.Map<v2.Conference>(v2Schedule.Event as v1.Conference); }
if (v2Schedule.Event is v1.ReligiousCeremony) { v2Schedule.Event = mapper.Map<v2.ReligiousCeremony>(v2Schedule.Event as v1.ReligiousCeremony); }

(I know about switching on object type, but that's a c#7 feature and I'm still in c#6.)

Upvotes: 0

Views: 212

Answers (1)

Yitz
Yitz

Reputation: 1306

Looking at the docs, it seems you can tell AutoMapper about the inheritance like so:

var config = new MapperConfiguration(cfg =>
    {
       //Other mapping

        cfg.CreateMap<v1.Event, v2.Event>() //or even <object, v2.Event>
            .Include<v1.Conference, v2.Conference>()
            .Include<v1.ReligiousCeremony, v2.ReligiousCeremony>();
            
        cfg.CreateMap<v1.Conference, v2.Conference>();
        cfg.CreateMap<v1.ReligiousCeremony, v2.ReligiousCeremony>();
    });

Upvotes: 1

Related Questions