how could I convert
Expression<Func<T,U>> fieldExpression = a=>a.Field1.Field2.Field3
to something like
Expression<Func<T, U>> fieldExpression =
a => a.Field1 != null
? a.Field1.Field2 != null
? a.Field1.Field2.Field3
: null
: null;
Is there any libs, or examples?
I have a lot of Expressions> looks like
Expression<Func<T,U>> fieldExpression = a=>a.(Field1 as SomeType).Field2.Field3
It used as “Virtual Field” Expressions in LINQ Queries, so when I use it in Select() it works ok when one of FieldN is NULL.
Another usage of this expression is to compile Func<T,U> to extract value from object. So when I use fieldExpression.Compile()(myObject) and one of FieldN is NULL – I got NullReferenceException.
I know, that second expression is more universal and I can use only it, but it’s more complex and SQL generated by it is significantly slower
I have a blog post about doing exactly that: http://www.thomaslevesque.com/2010/02/21/automating-null-checks-with-linq-expressions/