Search code examples
c#collectionsmappingautomapperautomapper-6

Automapper - exclude some objects from mapped collection


I have the following map rules:

CreateMap<ViewModels.ApplicationDriverAccidentFormVM, ApplicationDriverAccidentDomain>();

then I want to map ViewModels.ApplicationDriverFormVM to ApplicationDriverDomain, both are have Accidents property, which are appropriate collections for each type.

public class ApplicationDriverDomain
{
    public List<ApplicationDriverAccidentDomain> Accidents { get; set; }
}

public class ApplicationDriverFormVM
{
    public List<ApplicationDriverAccidentFormVM> Accidents { get; set; }
}

And I want to exclude (not map) all records, which are not satisfied some conditions I try to write the following code:

        CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>()
            .ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => GetNotNullFromCollection(src.Accidents)))

where GetNotNullFromCollection is:

    List<object> GetNotNullFromCollection(object input)
    {
        List<object> output = new List<object>();
        foreach (var item in (List<object>)input)
        {
            if (!Utils.IsAllNull(item))
                output.Add(item);
        }
        return output;
    }

but it says me:

Unable to cast object of type 'System.Collections.Generic.List1[Web.ViewModels.ApplicationDriverAccidentFormVM]' to type 'System.Collections.Generic.List1[System.Object]'.

Why and how to do it?


Solution

  • I solved it by the following way:

    CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>().ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => src.Accidents.Where(o => !Utils.IsAllNull(o))))