John S
John S

Reputation: 8341

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. i.e. 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.

Upvotes: 0

Views: 1681

Answers (1)

Joseph Evensen
Joseph Evensen

Reputation: 171

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

Upvotes: 2

Related Questions