c# - AutoMapper,尝试并捕获映射

标签 c# exception try-catch automapper

我已经创建了一个 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/

相关文章:

php - PHP自定义错误处理程序: How to determine if exception was generated within try{}catch{} block?

c# - WPF Prism + 现有 WPF 应用程序

c# - 将二进制文件读入结构

c# - 引用多个 API 扩展时,无法在 "Release"中构建 W10 UWP 应用

c# - ASP.NET MVC - 在默认帐户系统中删除用户?

c# - try catch 异步异常

wpf - 如何处理WPF应用程序实例化过程中抛出的异常?

python - 查找异常前最后尝试的指令

javascript - 如何使用常见的 try-catch 来处理 Javascript 中的每个给定函数?

powershell - 如何将2个错误输出合并为一个