简体   繁体   中英

Use AutoMapper for mapping Nested Class Property along with Base Class

How can I Map Nested Classes using AutoMapper in c#,

I am having Classes like..

public class Source{
public int Id {get;set;}
public Address Address {get;set;}
}

public class Dest{
public int Id {get;set;}
public AddressModel Address {get;set;}
}

How can I map Source And Dest class with Address and AddressModel Mapped I am new to AutoMapper Please Help...

My Mapping Looks as below right now.

CreateMap<Source,Dest>().ForMember(dest=>dest.AddressModel,opt=>opt.MapFrom(src=>src.Address)).ReverseMap();

Automapper automatically maps child properties if both source and destination have same name of the child properties ie

public class Source
    {
        public int Id { get; set; }
        public Address Address { get; set; }
    }

    public class Dest
    {
        public int Id { get; set; }
        public AddressModel Address { get; set; }
    }

    public class Address
    {
        public string Name { get; set; }
    }

    public class AddressModel
    {
        public string Name { get; set; }
    }

Mapping

CreateMap<Source, Dest>().ReverseMap();

UseCase

var source = new Source { Id = 1, Address = new Address { Name = "A" } };
var dest = _mapper.Map<Dest>(source);

Here you will get address object in dest variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM