Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

automapper

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?

like image 455
Vince Avatar asked Dec 19 '25 12:12

Vince


1 Answers

I believe Automapper provides this:

private static void CreateMappings(IMapperConfiguration config)
{
  config.CreateMap<SrcRow, DestDto>()
  .ForAllMembers(opt => opt.ResolveUsing(
    ...
  ); // or use opt.Condition()
}
like image 139
JDupont Avatar answered Dec 21 '25 01:12

JDupont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!