Vince
Vince

Reputation: 637

AutoMapper how to ignore exception when getting a property that throws exception?

I have a source object which derives from System.Data.DataRow whose string properties will throw exceptions on Get if the underlying value is DBNull

private static void CreateMappings(IMapperConfiguration config)
{
    config.CreateMap<SrcRow, DestDto>()
    .ForMember(d => d.Error_Text, opt => opt.ResolveUsing(row =>
        {
            try
            {
                // the getter of this string property throws exception if internal value is DBNull
                return row.error_text;
            }
            catch
            {
                return null;
            }
        }))
    ;

}

All the source and destination properties are string. The source object is a wrapper around a DataRow and each property gets a particular row value. If the row value is DBNull value, the property getter throws an exception. How can I achieve this code but for all members of the destination type instead of copy/pasting this code for each member?

Upvotes: 3

Views: 2502

Answers (2)

JDupont
JDupont

Reputation: 1352

I believe Automapper provides this:

private static void CreateMappings(IMapperConfiguration config)
{
  config.CreateMap<SrcRow, DestDto>()
  .ForAllMembers(opt => opt.ResolveUsing(
    ...
  ); // or use opt.Condition()
}

Upvotes: 1

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

One way to do this is using ForAllMembers() method and create a condition to map the value only if the source doesn't throw an exception:

config.CreateMap<SrcRow, DestDto>().ForAllMembers(opts => opts.Condition(rc => 
{
    try  { return rc.SourceValue != null; } // Or anything, just try to get the value. 
    catch { return false; }
}));

Upvotes: 0

Related Questions