我有一个项目,我试图使用 AutoMapper 从多个类进行映射,每个类中都有一些属性,我想使用一些自定义逻辑将源值解析到目标。
我尝试使用 AutoMapper 文档中记录的自定义解析器方法。
这是我的代码:
public class CustomDateTextHandler : IValueResolver<object, object, string>
{
public string Resolve(object source, object destination, string destMember, ResolutionContext context)
{
string txt = source.ToString();
txt.Replace("AM/PM", "tt");
txt.Replace("HH:MM", "hh:mm");
if (txt.Contains("format"))
{
txt.Replace("mmm", "MMM");
}
return txt;
}
}
public class SMapping : Profile
{
public SMapping()
{
CreateMap<SourceForm, s_form>()
.ForMember(dest => dest.id, opt => opt.Ignore())
.ForMember(dest => dest.cell_text, opt => opt.MapFrom<CustomDateTextHandler>())
.ForMember(dest => dest.fn_def, opt => opt.MapFrom<CustomCodeTextResolver>());
}
我想要获取的是用解析器方法中的替换逻辑处理的 cell_text 值,但我面临的问题是传递给解析器的是整个 SMapping 实例,我希望能够重用解析器跨不同类的代码,其中属性名称会有所不同,但是看看目前发生的情况,我无法真正在不同的类中使用解析器代码。
有人能帮我吗?
先感谢您。
使用 IMemberValueResolver 而不是 IValueResolver。
与IValueResolver相比,它的Resolve函数多了一个参数:value。
使用 IMemberValueResolver 注册映射需要您传递 1 个额外参数 - 不是直接“值”,而是一个将从给定源对象生成“值”的 lambda。
public class CustomDateTextHandler :
IMemberValueResolver< // note: different interface
object, object,
string, string // note: 1 more parameter
>
{
public string Resolve(
object source, object destination,
string sourceValue, string destMember, // note: 1 more parameter
ResolutionContext context
)
{
// here, see the difference:
// source - source object, whole
// sourceMember - value produced by extra lambda passed in mapping
}
}
public class SMapping : Profile
{
public SMapping()
{
CreateMap<SourceForm, s_form>()
...
.ForMember(
dest => dest.cell_text,
opt => opt.MapFrom<CustomDateTextHandler, string>(source => source.PROPERTY11)) // note: this produces that sourceValue
.ForMember(
dest => dest.fn_def,
opt => opt.MapFrom<CustomCodeTextResolver, string>(source => source.PROPERTY22)); // note: this produces that sourceValue
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)