Created
April 27, 2011 14:31
-
-
Save jagregory/944344 to your computer and use it in GitHub Desktop.
NullSafeMapFrom extension for AutoMapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} | |
} |
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.
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
This'll silently catch any
NullReferenceException
s 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:
Obviously, it should use expression caching in high throughput environments. YMMV.