AutoMapper - 强类型数据集

red*_*man 5 c# strongly-typed-dataset automapper

我有这样定义的映射:

Mapper.CreateMap<DsMyDataSet.TMyRow, MyRowDto>();
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我打电话的时候:

DsMyDataSet.TMyRow row = ....;
AutoMapper.Mapper.Map<MyRowDto>(row);
Run Code Online (Sandbox Code Playgroud)

我得到StrongTypingException异常,因为列中的值为null.该属性可以为空,但强类型数据集不支持可空属性,您必须调用IsNullable instea.如何在AutoMapper中解决此问题,以便映射进行(忽略错误并保留空值)?

sma*_*man 2

我认为解决这个问题的最简单方法是使用该IMemberConfigurationExpression<DsMyDataSet.TMyRow>.Condition()方法并使用try-catch块来检查访问源值是否抛出StrongTypingException.

您的代码最终将如下所示:

Mapper.CreateMap<DsMyDataSet.TMyRow, MyRowDto>()
      .ForMember( target => target.PositionFolder,
        options => options.Condition(source => { 
             try { return source.PositionFolder == source.PositionFolder; }
             catch(StrongTypingException) { return false; } 
      });
Run Code Online (Sandbox Code Playgroud)

如果这种情况很常见,那么您还有其他一些选择来避免为每个成员编写所有这些代码。

一种方法是使用扩展方法:

Mapper
.CreateMap<Row,RowDto>()
.ForMember( target => target.PositionFolder, options => options.IfSafeAgainst<Row,StrongTypingException>(source => source.PositionFolder) )
Run Code Online (Sandbox Code Playgroud)

当解决方案中有以下内容时:

 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; }
         });
     }
 } 
Run Code Online (Sandbox Code Playgroud)

AutoMapper 还具有一些内置的扩展点,也可以在这里利用。我突然想到的几种可能性是:

  1. 定义自定义IValueResolver实现。解决方案中已经有一个类似的实现可供您使用:NullReferenceExceptionSwallowingResolver. 您可能可以复制该代码,然后只需更改指定您正在处理的异常类型的部分。 配置文档位于 AutoMapper wiki 上,但配置代码如下所示:

    Mapper.CreateMap<Row,RowDto>()
      .ForMember( target => target.PositionFolder, 
            options => options.ResolveUsing<ExceptionSwallowingValueResolver<StrongTypingException>>());
    
    Run Code Online (Sandbox Code Playgroud)