我有这样定义的映射:
Mapper.CreateMap<DsMyDataSet.TMyRow, MyRowDto>();
MyRowDto 是 TMyRow 的 1:1 副本,但所有属性都是自动属性。
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string PositionFolder{
get {
try {
return ((string)(this[this.tableTMyDataSet.PositionFolderColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'PositionFolder\' in table \'TMyDataSet\' is DBNull.", e);
}
}
set {
this[this.tableTMyDataSet.PositionFolderColumn] = value;
}
}
当我打电话时:
DsMyDataSet.TMyRow row = ....;
AutoMapper.Mapper.Map<MyRowDto>(row);
我收到 StrongTypingException 异常,因为该列中的值为空。该属性是可为空的,但强类型数据集不支持可为空的属性,您必须调用 IsNullable instea。 我如何在 AutoMapper 中解决这个问题,以便进行映射(忽略错误并保留空值)?
最佳答案
我认为解决这个问题最简单的方法是使用 IMemberConfigurationExpression<DsMyDataSet.TMyRow>.Condition()
方法并使用 try-catch
block 以检查访问源值是否抛出 StrongTypingException
.
这是您的代码最终的样子:
Mapper.CreateMap<DsMyDataSet.TMyRow, MyRowDto>()
.ForMember( target => target.PositionFolder,
options => options.Condition(source => {
try { return source.PositionFolder == source.PositionFolder; }
catch(StrongTypingException) { return false; }
});
如果这种情况很常见,那么您还有其他一些选择可以避免为每个成员编写所有这些代码。
一种方法是使用扩展方法:
Mapper
.CreateMap<Row,RowDto>()
.ForMember( target => target.PositionFolder, options => options.IfSafeAgainst<Row,StrongTypingException>(source => source.PositionFolder) )
当以下内容在解决方案中时:
public static class AutoMapperSafeMemberAccessExtension
{
public static void IfSafeAgainst<T,TException>(this IMemberConfigurationExpression<T> options, Func<T,object> get)
where TException : Exception
{
return options.Condition(source => {
try { var value = get(source); return true; }
catch(TException) { return false; }
});
}
}
AutoMapper 也有一些内置的扩展点,也可以在这里利用。我突然想到的几种可能性是:
定义自定义
IValueResolver
执行。您可以使用的解决方案中已经有一个类似的实现:NullReferenceExceptionSwallowingResolver
.您可能会复制该代码,然后只更改指定您正在处理的异常类型的部分。 Documentation for configuration is on the AutoMapper wiki ,但配置代码看起来像这样:Mapper.CreateMap<Row,RowDto>() .ForMember( target => target.PositionFolder, options => options.ResolveUsing<ExceptionSwallowingValueResolver<StrongTypingException>>());
关于c# - AutoMapper - 强类型数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123464/