[英]AutoMapper - set a destination property to null when source property is not available
[英]AutoMapper set destination to null on condition of source property
我在兩個對象之間進行映射,並根據源的條件我希望目標為空。
例如,這里是類:
public class Foo
{
public int Code { get; set; }
public string Name { get; set; }
}
public class Bar
{
public string Name { get; set; }
public string Type { get; set; }
}
還有我的地圖:
Mapper.CreateMap<Foo, Bar>()
.AfterMap((s, d) => { if (s.Code != 0) d = null; });
但它似乎忽略了 AfterMap。 Bar 已初始化,但具有所有默認屬性。
如何讓映射器根據代碼不等於 0 返回 null?
謝謝
一種可能的方法是——
class Converter : TypeConverter<Foo, Bar>
{
protected override Bar ConvertCore(Foo source)
{
if (source.Code != 0)
return null;
return new Bar();
}
}
static void Main(string[] args)
{
Mapper.CreateMap<Foo, Bar>()
.ConvertUsing<Converter>();
var bar = Mapper.Map<Bar>(new Foo
{
Code = 1
});
//bar == null true
}
我創建了以下擴展方法來解決這個問題。
public static IMappingExpression<TSource, TDestination> PreCondition<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mapping
, Func<TSource, bool> condition
)
where TDestination : new()
{
// This will configure the mapping to return null if the source object condition fails
mapping.ConstructUsing(
src => condition(src)
? new TDestination()
: default(TDestination)
);
// This will configure the mapping to ignore all member mappings to the null destination object
mapping.ForAllMembers(opt => opt.PreCondition(condition));
return mapping;
}
對於有問題的情況,它可以這樣使用:
Mapper.CreateMap<Foo, Bar>()
.PreCondition(src => src.Code == 0);
現在,如果條件失敗,映射器將返回 null; 否則,它將返回映射對象。
我更喜歡自定義值解析器。 這是我的看法...
public class CustomValueResolver : IValueResolver<Foo, Bar, string>
{
public string Resolve(Foo source, Bar destination, string destMember, ResolutionContext context)
{
return source.Code != 0 ? null : "asd";
}
}
public class YourProfile : Profile
{
public YourProfile()
{
this.CreateMap<Foo, Bar>()
.ForMember(dst => dst.Name, opt => opt.MapFrom<CustomValueResolver>())
// ...
;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.