Reputation: 637
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
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
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