How to convert lambda expressions to and from using boolean types

1

I was using the lambda expression conversion class from How can I convert a lambda-expression between different (but compatible) models? class name "TypeConversionVisitor". It's working well with model queries. When am trying to convert the below it's throwing exceptions.The below is the exception.

Exception:
System.InvalidOperationException
  HResult=0x80131509
  Message=The binary operator Equal is not defined for the types 'System.Nullable`1[System.Boolean]' and 'System.Boolean'.
  Source=System.Linq.Expressions
  StackTrace:
   at System.Linq.Expressions.Expression.GetEqualityComparisonOperator(ExpressionType binaryType, String opName, Expression left, Expression right, Boolean liftToNull)
   at System.Linq.Expressions.Expression.Equal(Expression left, Expression right, Boolean liftToNull, MethodInfo method)
   at System.Linq.Expressions.BinaryExpression.Update(Expression left, LambdaExpression conversion, Expression right)
   at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
   at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
   at Common.LinqExpressionConverter.ConvertImpl[TFrom,TTo](Expression`1 from) in    at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()

Code :

public partial class CompanyHolidaysQuery
{

    public int HolidayID { get; set; }
    public DateTime HolidayDate { get; set; }
    public string Description { get; set; }
    public bool ActiveFlag { get; set; }
    public int? ApplicationTypeID { get; set; }
}

public partial class CompanyHolidays
{

    public int HolidayID { get; set; }
    public DateTime HolidayDate { get; set; }
    public string Description { get; set; }
    public bool ActiveFlag { get; set; }
    public int? ApplicationTypeID { get; set; }
}
 Expression<Func<CompanyHolidaysQuery, bool>> filter = x => x.ApplicationTypeID == 3 && x.ActiveFlag = true;

 Expression<Func<CompanyHolidays, bool>> switched = filter.Convert<CompanyHolidaysQuery, CompanyHolidays>();     
 

Any help is appreciated.

Thanks Roopesh

c#
.net
lambda
asked on Stack Overflow Nov 5, 2020 by Roopesh Chadalavada • edited Nov 5, 2020 by adjan

1 Answer

1

ApplicationTypeID is nullable, so check it for a value before comparing:

x => x.ApplicationTypeID.HasValue &&  x.ApplicationTypeID.Value == 3 && x.ActiveFlag
answered on Stack Overflow Nov 6, 2020 by Jonathan • edited Nov 6, 2020 by Jonathan

User contributions licensed under CC BY-SA 3.0