AutoMapper,尝试捕捉映射
AutoMapper,try and catch mapping
我已经创建了一个地图,但是......一些源属性会不时抛出异常(不要问我为什么有人决定让 "get" 在它为 null 时抛出异常。 .但是好吧..)
当 AutoMapper 尝试映射属性时,这会导致一些问题,是否有尝试捕获映射中的异常,如果它进入缓存,则只需将默认值分配给目标 -属性?
Br,
指数
你有没有考虑过
Automapper.Mapper.CreateMap<Source,Dest>().BeforeMap(Action<Source, Dest> beforeMapAction)`
?
来自https://github.com/AutoMapper/AutoMapper/wiki/Before-and-after-map-actions
Occasionally, you might need to perform custom logic before or after a map occurs. These should be a rarity, as it's more obvious to do this work outside of AutoMapper. You can create global before/after map actions:
Mapper.CreateMap<Source, Dest>()
.BeforeMap((src, dest) => src.Value = src.Value + 10)
.AfterMap((src, dest) => dest.Name = "John");
Or you can create before/after map callbacks during mapping:
int i = 10;
Mapper.Map<Source, Dest>(src, opt => {
opt.BeforeMap((src, dest) => src.Value = src.Value + i);
opt.AfterMap((src, dest) => dest.Name = HttpContext.Current.Identity.Name);
});
The latter configuration is helpful when you need contextual information fed into before/after map actions.
首先,您必须添加 属性 以忽略列表,然后在地图之前使用。
AutoMapper.Mapper.CreateMap<Source,Dest>().
ForMember((src => src.PropertyWithException), opt => opt.Ignore()).
BeforeMap((src,dest)=>
{
try
{
dest.PropertyWithException = src.PropertyWithException;
}
catch
{
dest.PropertyWithException = some_default_value;
}
});
我已经创建了一个地图,但是......一些源属性会不时抛出异常(不要问我为什么有人决定让 "get" 在它为 null 时抛出异常。 .但是好吧..) 当 AutoMapper 尝试映射属性时,这会导致一些问题,是否有尝试捕获映射中的异常,如果它进入缓存,则只需将默认值分配给目标 -属性?
Br, 指数
你有没有考虑过
Automapper.Mapper.CreateMap<Source,Dest>().BeforeMap(Action<Source, Dest> beforeMapAction)`
?
来自https://github.com/AutoMapper/AutoMapper/wiki/Before-and-after-map-actions
Occasionally, you might need to perform custom logic before or after a map occurs. These should be a rarity, as it's more obvious to do this work outside of AutoMapper. You can create global before/after map actions:
Mapper.CreateMap<Source, Dest>() .BeforeMap((src, dest) => src.Value = src.Value + 10) .AfterMap((src, dest) => dest.Name = "John");
Or you can create before/after map callbacks during mapping:
int i = 10; Mapper.Map<Source, Dest>(src, opt => { opt.BeforeMap((src, dest) => src.Value = src.Value + i); opt.AfterMap((src, dest) => dest.Name = HttpContext.Current.Identity.Name); });
The latter configuration is helpful when you need contextual information fed into before/after map actions.
首先,您必须添加 属性 以忽略列表,然后在地图之前使用。
AutoMapper.Mapper.CreateMap<Source,Dest>().
ForMember((src => src.PropertyWithException), opt => opt.Ignore()).
BeforeMap((src,dest)=>
{
try
{
dest.PropertyWithException = src.PropertyWithException;
}
catch
{
dest.PropertyWithException = some_default_value;
}
});