Skip to content

Instantly share code, notes, and snippets.

@jagregory
Created April 27, 2011 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagregory/944344 to your computer and use it in GitHub Desktop.
Save jagregory/944344 to your computer and use it in GitHub Desktop.
NullSafeMapFrom extension for AutoMapper
public static class AutoMapperExtensions
{
public static void NullSafeMapFrom<T, TResult>(this IMemberConfigurationExpression<T> opt, Expression<Func<T, TResult>> sourceMemberExpression)
{
var sourceMember = sourceMemberExpression.Compile();
opt.MapFrom(src =>
{
try
{
return sourceMember(src);
}
catch (NullReferenceException)
{}
return default(TResult);
});
}
}
@jagregory
Copy link
Author

This'll silently catch any NullReferenceExceptions that might get thrown from null properties in a call chain. Expression is (sadly) necessary to stop Visual Studio from moaning about the exception being unhandled.

Usage:

.ForMember(dest => dest.Target, opt => opt.NullSafeMapFrom(src => src.Something.That.Will.Throw))

Obviously, it should use expression caching in high throughput environments. YMMV.

@jbogard
Copy link

jbogard commented Apr 27, 2011

You know, I've been looking to split out a MapFrom that uses expressions and a ResolveUsing that uses Func, for this very reason. It also lets me "know" the TResult a little easier.

@senglory
Copy link

Hi,

Tried to compile your code both in VS2010 for .NET 4.0 and in VS2013 for .NET 4.5.1 - result is the same on line 10:

error CS0834: A lambda expression with a statement body cannot be converted to an expression tree

What I'm doing wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment