Micah
Micah

Reputation: 116070

Mapping complex models with Automapper

Here's my original model:

public class MyClass
{
   public string Name{get;set;}
   public double Latitude{get;set;}
   public double Longitude{get;set;}
   public string Street{get;set;}
   public string City{get;set;}
   public string State{get;set;}
   public string Zip{get;set;}
}

And I want to map it to this for JSON serialization purposes:

public class MyNewClass
{
    public string Name{get;set;}
    public Location{get;set;}
}

public class Location
{
   public string Street{get;set;}
   public string City{get;set;}
   public string State{get;set;}
   public string Zip{get;set;}
   public Coordinates Coordinates{get;set;}
}

public class Coordinates
{
   public double Latitude{get;set;}
   public double Longitude{get;set;}
}

I can't seem to figure out the right way to configure the mapping.

Upvotes: 1

Views: 269

Answers (1)

Micah
Micah

Reputation: 116070

I was able to finally figure it out. Each object needs to be explicity mapped.

    Mapper.CreateMap<MyClass, Coordinates>();
    Mapper.CreateMap<MyClass, Location>().ForMember(dest => dest.Coordinates, opt => opt.MapFrom(src => src));
    Mapper.CreateMap<MyClass, MyNewClass>().ForMember(dest => dest.Location, opt => opt.MapFrom(src => src));

Upvotes: 1

Related Questions