-1

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;
}
mattpm
  • 1,310
  • 2
  • 19
  • 26
  • 2
    If you don't care about the internal structure of the `Expression<>` then just use a `Func<>` and let the C# compiler do the compiling for you. – Jeremy Lakeman Nov 09 '22 at 01:05
  • Cheers Jeremy. I'll look into who I might adopt that approach instead. Just clarifying, by Func<> you're suggesting I just make the parameter Func and call Invoke on the Func parameter right? – mattpm Nov 09 '22 at 01:19

1 Answers1

1

You will have to do this for the expression,

p => p.MySubEntity == null ? "" : p.MySubEntity.Description

because

An expression tree lambda may not contain a null propagating operator

see this post

Charles Han
  • 1,920
  • 2
  • 10
  • 19