c# - 如何在 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>();
任何帮助表示赞赏。
谢谢鲁佩什
解决方案
ApplicationTypeID
可以为空,所以在比较之前检查它的值:
x => x.ApplicationTypeID.HasValue && x.ApplicationTypeID.Value == 3 && x.ActiveFlag
推荐阅读
- javascript - vue-bootstrap-datetimepicker 中缺少指向下个月和上个月的箭头?
- docker - 在另一个容器的构建过程中无法解析 docker 容器
- ios - 从 UIDocumentBrowserViewController 获取 UIActivityViewController 的 sourceRect
- javascript - Javascript - 比较两个数组对象并附加值
- python - TensorFlow中的特定线性分类器:输入元素作为向量
- reactjs - 一个屏幕上有多个带有过滤器的 React 管理员列表
- javascript - 检查提及是否是用户 - 不和谐
- python - 使用python将sticky位分配给linux组权限
- docker - 安装 Catalina 后 Docker Sync 无法启动
- pandas - TfidfTransformer.fit_transform(数据帧)失败