C# 自动映射-从映射集合中排除某些对象

C# 自动映射-从映射集合中排除某些对象,c#,collections,mapping,automapper,automapper-6,C#,Collections,Mapping,Automapper,Automapper 6,我有以下地图规则: CreateMap<ViewModels.ApplicationDriverAccidentFormVM, ApplicationDriverAccidentDomain>(); CreateMap(); 然后我想将ViewModels.ApplicationDriverFormVM映射到ApplicationDriverDomain,两者都是havecontractions属性,它们是每种类型的适当集合 public class ApplicationDri

我有以下地图规则:

CreateMap<ViewModels.ApplicationDriverAccidentFormVM, ApplicationDriverAccidentDomain>();
CreateMap();
然后我想将ViewModels.ApplicationDriverFormVM映射到ApplicationDriverDomain,两者都是havecontractions属性,它们是每种类型的适当集合

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

public class ApplicationDriverFormVM
{
    public List<ApplicationDriverAccidentFormVM> Accidents { get; set; }
}
公共类应用程序域
{
公共列表事故{get;set;}
}
公共类ApplicationDriverFormVM
{
公共列表事故{get;set;}
}
我想排除(不是映射)所有不满足某些条件的记录 我尝试编写以下代码:

        CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>()
            .ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => GetNotNullFromCollection(src.Accidents)))
CreateMap()
.FormMember(dest=>dest.contractions,opt=>opt.MapFrom(src=>GetNotNullFromCollection(src.contractions)))
其中GetNotNullFromCollection是:

    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;
    }
列出GetNotNullFromCollection(对象输入)
{
列表输出=新列表();
foreach(列表输入中的var项)
{
如果(!Utils.IsAllNull(项))
输出。添加(项目);
}
返回输出;
}
但它告诉我:

无法强制转换类型为的对象 'System.Collections.Generic.List
1[Web.ViewModels.ApplicationDriverAccidentFormVM]'
键入“System.Collections.Generic.List
1[System.Object]”


为什么以及如何执行此操作?

您的方法
GetNotNullFromCollection
接收一个对象,但您正在向其传递一个列表。
无论如何,我建议使用而不是对象

我用以下方法解决了这个问题:

CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>().ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => src.Accidents.Where(o => !Utils.IsAllNull(o))))
CreateMap().formMember(dest=>dest.contractions,opt=>opt.MapFrom(src=>src.contractions.Where(o=>!Utils.IsAllNull(o)))
List不是对象?List是泛型类型的列表,而不是对象。请阅读更多关于泛型的主题