Automapper map from Source to Destination containing List of Objects
Asked Answered
H

2

5

I have to create a Mapping with automapper.

Public class Source
{
    public string Id;
    public string Firstname;
    public string Lastname;
}

Destination is

Public class Destination
{
    public string Id;
    public Person[] persons;
}

Person Class is

Public class Person
{
    public string FirstName;
    public string LastName;
}

I am trying to create mapping

AutoMapper.Mapper.CreateMap<Source, Destination>(); 

but I don't know how to map Firstname, Lastname to array of object Person.

Hopping answered 19/2, 2014 at 10:23 Comment(0)
B
7
AutoMapper.Mapper.CreateMap<Source, Destination>().AfterMap((s,d) => d.Person = new Person[] { FirstName = s.FirstName, LastName = s.LastName }));

This solution should create a new instance of Person however would you not be better off mapping them to a new class rather than an array?

Button answered 19/2, 2014 at 10:54 Comment(0)
H
0

I solved it .

AutoMapper.Mapper.CreateMap<Source, Destination>()
                .AfterMap((s, d) => d.persons= new Person[1])
                .AfterMap((s, d) => d.persons[0] = new Person{ FirstName= s.FirstName, LastName= s.LastName, RemoteId = s.Name 
                ;
Hopping answered 19/2, 2014 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.