![](/img/trans.png)
[英]How to configure AutoMapper for Polymorphism with explicit member mapping?
[英]How to configure Conditional Mapping in AutoMapper?
假设我有以下实体(类)
public class Target
{
public string Value;
}
public class Source
{
public string Value1;
public string Value2;
}
现在我想配置自动映射,如果 Value1 以“A”开头,则将 Value1 映射到 Value,否则我想将 Value2 映射到 Value。
这是我到目前为止:
Mapper
.CreateMap<Source,Target>()
.ForMember(t => t.Value,
o =>
{
o.Condition(s =>
s.Value1.StartsWith("A"));
o.MapFrom(s => s.Value1);
<<***But then how do I supply the negative clause!?***>>
})
然而,我仍然无法理解的部分是如何告诉 AutoMapper 在早期条件失败时采用s.Value2
。
在我看来,API 的设计并没有达到应有的水平……但可能是我缺乏知识造成了障碍。
试试这个
Mapper.CreateMap<Source, Target>()
.ForMember(dest => dest.Value,
opt => opt.MapFrom
(src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2));
Condition 选项用于向在映射该属性之前必须满足的属性添加条件,而 MapFrom 选项用于执行自定义源/目标成员映射。
AutoMapper 允许向在映射该属性之前必须满足的属性添加条件。
Mapper.CreateMap<Source,Target>()
.ForMember(t => t.Value, opt =>
{
opt.PreCondition(s => s.Value1.StartsWith("A"));
opt.MapFrom(s => s.Value1);
})
使用条件映射,您只能配置何时应为指定的目标属性执行映射。
所以这意味着你不能为同一个目标属性定义两个具有不同条件的映射。
如果您有类似“如果条件为真,则使用 PropertyA,否则使用 PropertyB”之类的条件,那么您应该像“Tejal”写道的那样:
opt.MapFrom(src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2)
AutoMapper 允许您向在映射该属性之前必须满足的属性添加条件。
我正在使用一些枚举条件进行映射,看看我这边对社区来说是什么努力。
}
.ForMember(dest => dest.CurrentOrientationName,
opts => opts.MapFrom(src => src.IsLandscape?
PageSetupEditorOrientationViewModel.Orientation.Landscape :
PageSetupEditorOrientationViewModel.Orientation.Portrait));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.