来自多个源字段的自动映射器条件映射 [英] Automapper conditional map from multiple source fields
问题描述
我有一个类似于以下的源类:
I've got a source class like the following:
public class Source
{
public Field[] Fields { get; set; }
public Result[] Results { get; set; }
}
并具有一个目标类,如:
And have a destination class like:
public class Destination
{
public Value[] Values { get; set; }
}
所以我想从EITHER Fields
或 Results
映射到 Values
,具体取决于哪一个不为null(只有一个将具有价值).
So I want to map from EITHER Fields
or Results
to Values
depending on which one is not null (only one will ever have a value).
我尝试了以下地图:
CreateMap<Fields, Values>();
CreateMap<Results, Values>();
CreateMap<Source, Destination>()
.ForMember(d => d.Values, opt =>
{
opt.PreCondition(s => s.Fields != null);
opt.MapFrom(s => s.Fields });
})
.ForMember(d => d.Values, opt =>
{
opt.PreCondition(s => s.Results != null);
opt.MapFrom(s => s.Results);
});
唯一的问题是,它看起来是否最后一个 .ForMember
映射不满足条件,它会擦除第一个映射中的映射结果.
Only issue with this is that it looks if the last .ForMember
map doesn't meet the condition it wipes out the mapping result from the first map.
我还考虑过将其作为条件运算符:
I also thought about doing it as a conditional operator:
opt =>opt.MapFrom(s => s.Fields!= null?s.Fields:s.Results)
但是显然它们是不同的类型,所以不要编译.
But obviously they are different types so don't compile.
如何根据条件从不同类型的源属性映射到单个属性?
How can I map to a single property from source properties of different types based on a condition?
谢谢
推荐答案
有一个 ResolveUsing()
方法,该方法可让您进行更复杂的绑定,并且可以使用 IValueResolver
或 Func
.像这样:
There is a ResolveUsing()
method that allows you for more complex binding and you can use a IValueResolver
or a Func
. Something like this:
CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, mo => mo.ResolveUsing<ConditionalSourceValueResolver>());
根据您的需求的价值解析器可能看起来像:
And the value resolver depending on your needs may look like:
public class ConditionalSourceValueResolver : IValueResolver<Source, Destination, Value[]>
{
public Value[] Resolve(Source source, Destination destination, Value[] destMember, ResolutionContext context)
{
if (source.Fields == null)
return context.Mapper.Map<Value[]>(source.Results);
else
return context.Mapper.Map<Value[]>(source.Fields);
}
}
这篇关于来自多个源字段的自动映射器条件映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!