我定义了源类和目标类之间的映射:
Mapper.CreateMap<Source, Target>();
如果null
上的某个属性设置为特定值,我希望映射返回Source
:
// If Source.IsValid = false I want the mapping to return null
Source s = new Source { IsValid = false };
Target t = Mapper.Map<Target>(s);
Assert.IsNull(t);
如何配置AutoMapper来实现这一目标?
答案 0 :(得分:2)
您可以像这样定义您的映射:
Mapper.CreateMap<Source, Target>().TypeMap
.SetCondition(r => ((Source)r.SourceValue).IsValid);
答案 1 :(得分:1)
修改强>
如果您希望地图输出空对象,我建议使用两级映射:第一级通过使用ConvertUsing
方法接管映射行为来决定是否返回空对象,如果需要映射,则将其推迟到内部映射引擎:
static void Main(string[] args)
{
var innerConfigurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
innerConfigurationStore.CreateMap<From, To>()
.ForMember(to => to.DestinationName, opt => opt.MapFrom(from => from.Active ? from.Name : (string)null));
var innerMappingEngine = new MappingEngine(innerConfigurationStore);
Mapper.CreateMap<From, To>()
.ConvertUsing(from => from.Active ? innerMappingEngine.Map<To>(from) : null)
;
WriteMappedFrom(new From() {Active = true, Name = "ActiveFrom"});
WriteMappedFrom(new From() {Active = false, Name = "InactiveFrom"});
}
static void WriteMappedFrom(From from)
{
Console.WriteLine("Mapping from " + (from.Active ? "active" : "inactive") + " " + from.Name);
var to = Mapper.Map<To>(from);
Console.WriteLine("To -> " + (to == null ? "null" : "not null"));
}
INITIAL ANSWER
在Automapper中使用条件映射非常简单,这里有一些示例代码
public class From
{
public bool Active { get; set; }
public string Name { get; set; }
}
public class To
{
public string DestinationName { get; set; }
}
static void Main(string[] args)
{
Mapper.CreateMap<From, To>()
.ForMember(to => to.DestinationName, opt => opt.MapFrom(from => from.Active ? from.Name : (string)null));
WriteMappedFrom(new From() {Active = true, Name = "ActiveFrom"});
WriteMappedFrom(new From() {Active = false, Name = "InactiveFrom"});
}
static void WriteMappedFrom(From from)
{
Console.WriteLine("Mapping from " + (from.Active ? "active" : "inactive") + " " + from.Name);
var to = Mapper.Map<To>(from);
Console.WriteLine("To -> " + (to.DestinationName ?? "null"));
}
在automapper中还有其他conditional mappings,但它们似乎只适用于基于约定的映射。但是,您可以查看文档以确认