c# - Mapping to single object from source with collection of object with Automapper -


i have customer object collection of addresses map customer view model single address view model. address collection want map view model selected specific value in address. i.e. 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 mapping address null. there way select specific object collection , map single object.

this works me.

cfg.createmap<customer, customervm>() .formember(dest => dest.address, address => address .mapfrom(src => src.addresses.firstordefault(add => add.type.id == 2))); 

nicely won't throw or map if there no address.type == 2


Comments