Search code examples
c#.netsql-serverlinqexpression-trees

Expression method for NULLIF (with Divide)


I am using C# 4.5.2. I Have to call a SumDenominator method as a denominator for an Expression.Divide method:

var SumDenominatorExpression = Expression.Call(
    null,
    SumDenominatorMethod,
    Parameter,
    SumDenominatorSelector
);

then later on the actual Expression.Divide reads:

var FractionExpression = Expression.Divide(
    SumNumeratorExpression,
    SumDenominatorExpression
);

if the denominator's selector generates zero then the divide by zero exception is thrown. I tried to solve this by converting the Sum expression into a Nullable<> but the Divide method doesn't swallow null values. And the SQLServer (my provider) doesn't have a NULLIF function (i.e. System.Data.Entity.SqlServer.SqlFunctions) that I can wrap a Call expression around.

How to people tackle zeros in the denominator with C# Expression trees?

UPDATE Here are the expression methods I ended up using:

 Expression.Condition(
   Expression.Equal(
     SumDenominatorExpression,
     Expression.Constant(0.0, typeof(double))
   ),
   Expression.Constant(0.0, typeof(double)),
   FractionExpression
 )

Solution

  • It sounds like you want EF to be able to translate this expression. That restricts the kinds of patterns we can use. The following should work:

    FractionExpression =
      (SumDenominatorExpression == 0)
         ? (int?)null /*default value - pick what you want*/
         : (SumNumeratorExpression / SumDenominatorExpression);
    

    (I'm writing the expression tree as C# for typing speed.)

    Since EF does not support trees that have variables you will need to use the SumDenominatorExpression expression twice. Hopefully SQL Server will optimize that and evaluate it only once.