C# AutoMapper基于外部值有条件地映射属性

C# AutoMapper基于外部值有条件地映射属性,c#,.net,automapper,C#,.net,Automapper,我有从API搜索方法返回的搜索结果,我希望尽可能短的响应内容长度 我还设置了AutoMapper,它本身可以很好地处理配置文件中配置的各种映射 搜索结果的一个属性可能相当重要,我不想包含这些数据,因为不可能总是需要这些数据。因此,在搜索条件中,我添加了一个标志来包含此属性 有没有一种方法可以基于其他外部因素有条件地映射属性 目前,在映射配置中,我告诉它忽略weighty属性,然后如果条件指定了它,我随后映射另一个集合并将其分配给搜索结果 e、 g.在映射配置文件中: this.CreateMap

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

我还设置了AutoMapper,它本身可以很好地处理配置文件中配置的各种映射

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

有没有一种方法可以基于其他外部因素有条件地映射属性

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

e、 g.在映射配置文件中:

this.CreateMap<myModel, myDto>()
    .ForMember((dto) => dto.BigCollection,
               (opt) => opt.Ignore())
this.CreateMap()
.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 = ...
    }
}
results.MyDtos=myModels.Select((m)=>Mapper.Map(m));
if(搜索条件,包括DebigCollection)
{
foreach(results.MyDtos中的MyDto到MyDto)
{
//从适当的模型映射权重属性。
myDto.BigCollection=。。。
}
}

如果您使用的是Automapper 5.0,则可以使用
IMappingOperationOptions
IValueResolver
将值从方法范围传递到映射器本身

以下是一个例子:

您的值解析程序:

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>()); 
});

IncludeBigCollectionValue
将被传递到值解析程序中,并根据您在其中写入的内容使用。

当您告诉“外部因素”您指的是哪个范围时?全局的东西(来自配置文件的东西)?或者从方法范围中传递的内容,您将在
映射中传递该内容。从方法范围-它将被传递到搜索条件对象中的方法中。
mapper.Map<YourDestinationType>(yourSourceObj, opt.Items.Add("IncludeBigCollection", IncludeBigCollectionValue));