我已经创建了一个 map ,但是..一些源属性会不时抛出异常(不要问我为什么有人决定让“get”在其为空时抛出异常..但是好吧。 .) 当 AutoMapper 尝试映射属性时,这会导致一些问题,是否有办法 try catch 映射中的异常,如果它进入缓存,则只需为目标属性分配一个默认值?
兄弟, 指数
最佳答案
你考虑过吗
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.
首先,您必须将属性添加到忽略列表,然后在 map 之前使用。
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;
}
});
关于c# - AutoMapper,尝试并捕获映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28602726/