AutoMapper - Mapping source object to nested object

user5979

How to map single object to nested object

The below one is my entity.

class Employee
{
    public string name { get; set; }
    public string city_name { get; set; }
    public string State_name { get; set; }
}

I want to map to

class Employee
{
    public string Name;
    public Location Location;
}

class Location
{
    public string City;

    public string State;
}

Please note that the property names are different. Can any one could help to map these using AutoMapper

Yong Shun

Solution 1: ForPath

1.1 Create Profile instance with inheriting from Profile and put the configuration in the constructor.

1.1.1 Using ForPath to map nested property.

public class EmployeeProfile : Profile
{
    public EmployeeProfile()
    {
        CreateMap<Employee, EmployeeDto>()
            .ForPath(dest => dest.Location.City, opt => opt.MapFrom(src => src.city_name))
            .ForPath(dest => dest.Location.State, opt => opt.MapFrom(src => src.State_name));
    }
}

1.2 Adding profile to mapper configuration

public static void Main()
{
    var config = new MapperConfiguration(cfg =>
    {

        cfg.AddProfile<EmployeeProfile>();

        // Note: Demo program to use this configuration rather with EmployeeProfile
        /*
        cfg.CreateMap<Employee, EmployeeDto>()
            .ForPath(dest => dest.Location.City, opt => opt.MapFrom(src => src.city_name))
            .ForPath(dest => dest.Location.State, opt => opt.MapFrom(src => src.State_name));
        */      
    });
    IMapper mapper = config.CreateMapper();
        
    var employee = new Employee{name = "Mark", city_name = "City A", State_name = "State A"};

    var employeeDto = mapper.Map<Employee, EmployeeDto>(employee);
}

Sample Solution 1 on .Net Fiddle


Solution 2: AfterMap

2.1 Create Profile instance with inheriting from Profile and put the configuration in the constructor.

2.1.1 Using AfterMap to perform mapping nested property after map occurs.

public class EmployeeProfile : Profile
{
    public EmployeeProfile()
    {
        CreateMap<Employee, EmployeeDto>()
            .AfterMap((src, dest) => { dest.Location = 
                    new Location {
                        City = src.city_name,
                        State = src.State_name
                    };
                });
    }
}

2.2 Adding profile to mapper configuration

public static void Main()
{
    var config = new MapperConfiguration(cfg =>
    {

        cfg.AddProfile<EmployeeProfile>();

        // Note: Demo program to use this configuration rather with EmployeeProfile
        /*
        cfg.CreateMap<Employee, EmployeeDto>()
            .AfterMap((src, dest) => { dest.Location = 
                    new Location {
                        City = src.city_name,
                        State = src.State_name
                    };
                });
        */      
    });
    IMapper mapper = config.CreateMapper();
        
    var employee = new Employee{name = "Mark", city_name = "City A", State_name = "State A"};

    var employeeDto = mapper.Map<Employee, EmployeeDto>(employee);
}

Sample Solution 2 on .Net Fiddle


References

  1. ForPath
  2. Profile Instances
  3. Before and After Map

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Mapping nested object with mapstruct

mapping nested object from fxml to object

Mapping and filtering a nested object

Automapper and mapping list within a complex object / nested mappings

Automapper: Conditional mapping based on Source object and ResolutionContext

Automapper: how to map nested object?

Dozer mapping not working for nested object

AutoMapper one source object to multiple destination objects

How to use AutoMapper to map destination object with a child object in the source object?

Automapper mapping nested objects

AutoMapper map source property into inner destination object

delegating Member mapping to child object with AutoMapper

Mapping through a nested object in React

Automapper If source is null, set destination object properties

Automapper map nested different object properties

How to map nested object in automapper without using inline mapping or multiple .ForMember?

AutoMapper mapping object types

Restkit 0.2 nested object mapping

ResKit Object Mapping nested objects

Automapper: mapping a single member on type object to Icollection of object

Automapper suddenly creates nested object

c# Automapper mapping string to 1st element of array in nested object

AutoMapper - Map source object as property in the destination object

Automapper chain / nested object mapping throw exception

How can I include a child object mapping using AutoMapper when the source objects have no inheritance relationship?

C# automapper nested object conditional map

Automapper ProjectTo is not mapping JsonB ColumnType of POCO Object

Mapping Nested Array Object

How to map nested object with AutoMapper?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive