首页 > 解决方案 > 如何在 lambda 表达式和布尔类型之间进行转换

问题描述

我正在使用如何在不同(但兼容)模型之间转换 lambda 表达式中的 lambda 表达式转换类?类名“TypeConversionVisitor”。它适用于模型查询。当我试图转换下面它抛出异常。下面是异常。

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()

代码 :

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>();     
 

任何帮助表示赞赏。

谢谢鲁佩什

标签: c#.netlambda

解决方案


ApplicationTypeID可以为空,所以在比较之前检查它的值:

x => x.ApplicationTypeID.HasValue &&  x.ApplicationTypeID.Value == 3 && x.ActiveFlag

推荐阅读