简体   繁体   中英

Mapping to single object from source with collection of object with Automapper

I have a customer object with a collection of addresses that I would like to map to a customer view model with a single address view model. The address from the collection that I want to map to the view model is selected by a specific value in the address. ie where type Id == 1

My Automapper config is:

 cfg.CreateMap<Customer, CustomerVM>()
        .ForMember(dest => dest.Address, opt => opt.MapFrom(src => src.Type.Id== 2).FirstOrDefault())
        .ReverseMap();   
 cfg.CreateMap<Address, AddressVM>()            
        .ForMember(dest => dest.Street,opt=>opt.MapFrom(src=>src.Street1))
        .ForMember(dest => dest.State,opt=>opt.MapFrom(src=>src.Region))
        .ForMember(dest => dest.Postal, opt => opt.MapFrom(src => src.PostalCode))

  public class Customer{
        public virtual ICollection<Address> Addresses{get; set;}
        }
  public class CustomerVM{
       public AddressVM Address{get; set;}
       }

This is mapping but the address is null . Is there a way to select a specific object from a collection and map it to single object.

This works for me.

cfg.CreateMap<Customer, CustomerVM>()
.ForMember(dest => dest.Address, address => address
.MapFrom(src => src.Addresses.FirstOrDefault(add => add.Type.Id == 2)));

Nicely it won't throw or map if there is no address.type == 2

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