AutoMapper根据外部值有条件地映射属性

本文关键字:映射 属性 有条件 外部 AutoMapper | 更新日期: 2023-09-27 17:53:42

我有从API搜索方法返回的搜索结果,我希望保持响应内容长度尽可能短。

我还设置了AutoMapper,它本身可以很好地与配置文件中配置的各种映射一起工作。

搜索结果的某个属性可能相当重要,我不想包含该数据,因为它不太可能总是需要的。因此,我在搜索条件中添加了一个标志来包含此属性。

是否有一种方法可以根据其他外部因素有条件地映射属性?

目前,在map配置中,我已经告诉它忽略weight属性,然后如果条件指定了它,我随后映射另一个集合并将其分配给搜索结果。

。在映射配置文件中:

this.CreateMap<myModel, myDto>()
    .ForMember((dto) => dto.BigCollection,
               (opt) => opt.Ignore())

,然后在代码中:

results.MyDtos = myModels.Select((m) => Mapper.Map<myDto>(m));
if (searchCriteria.IncludeBigCollection)
{
    foreach(MyDto myDto in results.MyDtos)
    {
        // Map the weighty property from the appropriate model.
        myDto.BigCollection = ...
    }
}

AutoMapper根据外部值有条件地映射属性

如果您使用的是Automapper 5.0,那么您可以使用IMappingOperationOptionsIValueResolver将值从方法作用域传递到映射器本身。

下面是一个例子:

Your Value Resolver:

class YourValueResolver : IValueResolver<YourSourceType, YourBigCollectionType>
{
    public YourBigCollectionType Resolve(YourSourceType source, YourBigCollectionType destination, ResolutionContext context)
    {
        // here you need your check
        if((bool)context.Items["IncludeBigCollection"])
        {
            // then perform your mapping
            return mappedCollection;
        }
        // else return default or empty
        return default(YourBigCollectionType);
    }
}

配置你的映射:

new MapperConfiguration(cfg =>
{
    cfg.CreateMap<YourSourceType, YourDestinationType>().ForMember(d => d.YourBigCollection, opt => opt.ResolveUsing<YourValueResolver>()); 
});

然后你可以调用Map方法:

mapper.Map<YourDestinationType>(yourSourceObj, opt.Items.Add("IncludeBigCollection", IncludeBigCollectionValue));

IncludeBigCollectionValue将被传递到值解析器中,并根据您在那里写的内容使用