1
public class Person {
        public string Name { get; set; }
        public int Age { get; set; }
}

public class Planet {
        public int Id { get; set; }
        public string Name { get; set; }
}

public class PersonView {
        public string Name { get; set; }
        public int Age { get; set; }
        public int PlanetId { get; set; }

I have a Collection of People:

IEnumerable<Person> people = new IEnumerable<Person>();

And one Planet:

Planet ours = new Planet(){
  Id=1,
  Name="Earth"
}

Input would be:

[
  {
  "Name": "George",
  "Age": 21
  },
  {
  "Name": "Lisa",
  "Age": 24
  },
  {
  "Name": "George",
  "Age": 18
  }
]

and

{
  "Id":1,
  "Name":"Earth"
}

With mapping something like this:

IEnumerable<PersonView> people =
                mapper.Map<Person, PersonView>(people)
                      .Map<Planet, PersonView>(people);
            

Output would be:

[
  {
  "Name": "George",
  "Age": 21,
  "PlanetId": 1
  },
  {
  "Name": "Lisa",
  "Age": 24,
  "PlanetId": 1
  },
  {
  "Name": "George",
  "Age": 18,
  "PlanetId": 1
  }
]

I want to map the PersonView (destination) type with the two source types People and Planet, is this possible?

I know how to Map two sources to one destination --> Automapper - Multi object source and one destination

But I don't know how I can do this when there is one object and one Collection to one Collection.

  • Can you provide a complete example including input and what you expect the output would be after mapping? It's hard to tell how `Person` and `Planet` relate to each other. And if the `PersonView` is relevant – devNull Aug 09 '20 at 21:10
  • @devNull I've added example input and output. – Moritz Kepplinger Aug 09 '20 at 21:21
  • What does this mean? "I want to map the Planet with the People Collection on a IEnumerable, is this possible?". Do you want to have a property `People` on the planet type? Or do you want to have kind of a dictionary from Planet-To-People? – Waescher Aug 09 '20 at 21:30
  • @Waescher I want to map the PersonView (destination) type with the two source types People and Planet. – Moritz Kepplinger Aug 09 '20 at 21:33

1 Answers1

2

You'll probably have to do multiple mappings for this to work with your current class structure. You could map the people to a collection of PersonView first. And then map the Planet into each of the PersonView results. For example:

IEnumerable<Person> persons = ...
Planet planet = ...
IEnumerable<PersonView> personViews = 
    mapper.Map<IEnumerable<PersonView>>(persons)
        .Select(v => mapper.Map<Planet, PersonView>(planet, v));
devNull
  • 3,849
  • 1
  • 16
  • 16