I'm trying to work out how to pass a Linq Expression to a method and get the value of the passed expression.
When p.MySubEntity is null, the code throws an exception (see comment below at relevant line).
Is it possible to test for this to prevent the exception? For instance, you can use the null propagation in expressions myobject.subOject?.property to handle the null case.
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public MySubEntity MySubEntity { get; set; }
}
public class MySubEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
private static void TestGetVal()
{
MyEntity p = new MyEntity();
var myvalue = GetVal(p, p => p.MySubEntity.Description);
}
public static object GetVal<TModel, TResult>(TModel model, Expression<Func<TModel, TResult>> expression)
{
Func<TModel, TResult> compiledDelegate = expression.Compile();
//The following line raises a NullReferenceException
//when there is a null in the expression tree
var result = compiledDelegate(model);
return result;
}