简体   繁体   中英

Mapping nested lists with automapper

This is my class setup. How do i map only Invalid=false for DTOReportObservation AND DTOReportObservationLocation items?

reports = Mapper.Map<List<Report>, List<DTOReport>>(userReports);

    public class DTOReport
    {
        public List<DTOReportObservation> Observations;
    }

        public class DTOReportObservation
    {
        public Guid ReportObservationID { get; set; }
        public Guid ReportID { get; set; }
        public bool Invalid { get; set; }

        public List<DTOReportObservationLocation> ObservationLocations;
    }

     public class DTOReportObservationLocation
    {
        public Guid ReportObservationLocationID { get; set; }
        public Guid ReportObservationID { get; set; }
        public bool Invalid { get; set; }
    }

 CreateMap<Report, DTOReport>(MemberList.Source)
                .ForMember(d => d.Observations, opt => opt.MapFrom(src => src.ReportObservations))
                //??ReportObservations.Locations

With automapper you shouldn't need to create maps of lists. You just create a map from one type to another and let automapper iterate over the collections.

Can you also clarify what you mean by Invalid=false seeing as Invalid is a guid type.

For mapping only when invalid is false you can use the conditional mapping. https://automapper.readthedocs.io/en/latest/Conditional-mapping.html .

For more info on lists see here in the docs about collections. https://automapper.readthedocs.io/en/latest/Lists-and-arrays.html

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