假设Date可以为null DateTime:
Mapper.CreateMap<SomeViewModels, SomeDTO>()
.ForMember(dest => dest.Date,
opt => opt.MapFrom(src =>
{
DateTime? finalDate = null;
if (src.HasDate == "N")
{
// so it should be null
}
else
{
endResult = DateTime.Parse(src.Date.ToString());
}
return finalDate;
}));
我得到的错误是:&#34;错误30带有语句主体的lambda表达式无法转换为表达式树。&#34;
当然,我完全清楚我可以简化查询,例如:
Mapper.CreateMap<SomeViewModels, SomeDTO>()
.ForMember(dest => dest.Date,
opt => opt.MapFrom(src => src.HasDate == "N" ? null : DateTime.Parse(src.Date.ToString())));
但是,如果我坚持要保留第一个例子的结构,因为我有更复杂的if else语句,第二个例子不能提供或至少不是非常易读的怎么办?
答案 0 :(得分:20)
使用ResolveUsing方法:
Mapper.CreateMap<SomeViewModels, SomeDTO>()
.ForMember(dest => dest.Date, o => o.ResolveUsing(Converter));
private static object Converter(SomeViewModels value)
{
DateTime? finalDate = null;
if (value.Date.HasDate == "N")
{
// so it should be null
}
else
{
finalDate = DateTime.Parse(value.Date.ToString());
}
return finalDate;
}
答案 1 :(得分:2)
在最新版本的AutoMapper中,ResolveUsing
已被删除。而是使用MapFrom的新重载:
void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction);
只需添加另一个lambda / function参数,就会分派给这个新的重载:
CreateMap<TSource, TDest>()
.ForMember(dest => dest.SomeDestProp, opt => opt.MapFrom((src, dest) =>
{
TSomeDestProp destinationValue;
// mapping logic goes here
return destinationValue;
}));