5

TL;DR

How do you create an Expression where

Expression.NodeType == ExpresionType.IsTrue || ExpresionType.IsFalse

Background Info

I am creating a custom version of EnumerableQuery, where I rewrite all expressions to handle Null checking. So that when unit testing EF Linq2Sql code as Linq2Objects, accessed null navigation properties do not throw an exception, but instead handle it gracefully.

I am trying to implement tests for all ExpressionType members. How can I create a expression syntax to create ExpressionType.IsTrue and ExpressionType.IsFalse node.

Github Project: Moqqer

Attempt 1. x => x

Where clause:

queryable.Where(x => x.L1.L2.L3.L4.L5.Boolean);

returns

ExpressionType.MemberAccess

Attempt 2. x => !(x && y)

The following Where clause:

queryable.Where(x => !(x.L1.L2.L3.L4.L5.Boolean && x.L1.L2.L3.L4.L5.Boolean));

returns

ExpressionType.Not
     ExpressionType.AndAlso
         Left = ExpressionType.MemberAccess
         Right = ExpressionType.MemberAccess

Attempt 3. x => true

Where clause

queryable.Where(x => true);

returns

ExpressionType.Constant

Comments

I am guessing these ExpressionType's are only used when manually creating expression trees, and want to return an expresison similar to ExpressionType.Constant(true) but with less overhead?

Michal Ciechan
  • 13,492
  • 11
  • 76
  • 118

1 Answers1

4

As far as I can tell, ExpressionType.IsTrue and ExpressionType.IsFalse represent the unary operators true and false respectively. They're not "lower overhead" stand-ins for the constant bools.

That said, I haven't been able to get an expression to "automatically" create one of these nodes. The compiler will simply emit a call to op_true which shows up as a ExpressionType.Call. So it looks like it really shows up when manually building expression trees. In fact, you can create this type by calling Expression.IsTrue( Expression e ).

Kyle
  • 6,500
  • 2
  • 31
  • 41