Expression.Equal-如何比较可空字段和不可空字段? [英] Expression.Equal - How to Compare Nullable and Non Nullable fields?

查看:461
本文介绍了Expression.Equal-如何比较可空字段和不可空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可为空的datetime字段,并且必须将string日期字段转换为可为null的日期时间类型(使用Expression)....我使用以下代码进行了此操作.

I have a nullable datetime field and I have to convert the string date field to a nullable datetime type (using Expression)....I did this using the below.

 Expression.Constant(Convert.ChangeType(value, Nullable.GetUnderlyingType(memberAccess.Type)));.

memberAccess(上面提到的)是成员表达式类型. (来自LinqExtensions.cs) 现在,在代码中,我正在使用Expression.Equal方法.

The memberAccess (mentioned above) is of type member expression. (From LinqExtensions.cs) Now In the code I am using Expression.Equal Method.

Expression.Equal(memberAccess, filter); 

这在这里失败,因为memberaccess类型可以为空,但filter.type不可以为空...

This fails here, as memberaccess type is nullable but filter.type is not nullable...

即使我尝试使用

ConstantExpression test = Expression.Constant(Nullable.GetUnderlyingType(memberAccess.Type)),

类型"是运行时",而不是日期时间".

the Type is Runtime and not DateTime.

如何使用Expression.Equal比较可为空的&非空字段?有什么办法可以将字符串类型转换为可为null的datetime字段?其中任何一种都可以解决我的问题.

How to use Expression.Equal to compare nullable & non nullable field? IS there any way to convert the string type to a nullable datetime field? Either one of this will resolve my issue.

推荐答案

好的.我是这样做的.

首先将类型(字符串转换为日期时间)

First Converted the type (string to datetime)

filter = Expression.Constant(
    Convert.ChangeType(value, memberAccess.Type.GetGenericArguments()[0]));

然后将该表达式转换为所需的类型

then converted this expression to the desired type

Expression typeFilter = Expression.Convert(filter, memberAccess.Type);

然后使用Expression.Equal(memberAccess, typeFilter)...

(memberAccess is MemberExpression,它从模型中获取属性类型)

(memberAccess is MemberExpression and it takes the property type from model)

这篇关于Expression.Equal-如何比较可空字段和不可空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆