gpt4 book ai didi

c# - LINQ 动态查询生成 'where AssignedUser is null'

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:29 25 4
gpt4 key购买 nike

我正在尝试构建动态表达式查询以仅获取列中具有 null 的行

where AssignedUser is null

,下面是我的代码,但它没有按照我的预期进行。任何人都可以阐明这个问题吗?

private Expression<Func<VwAssignmentActivities, bool>> GetIsNullExpressionEquals<T>(string propName, T value)
{
var item = Expression.Parameter(typeof(VwAssignmentActivities), "item");
var prop = Expression.Convert(Expression.Property(item, propName), value.GetType());

Expression body = Expression.Equal(prop, Expression.Constant(null, prop.Type));

return Expression.Lambda<Func<VwAssignmentActivities, bool>>(body, item);
}

感谢任何帮助

最佳答案

您收到的错误是因为您的 Nullable 中有一个值。 get 类型返回 Int32,即使变量是 Nullable。那么您正在尝试将 null 转换为 int。

假设您只关心查找空值,我会做这样的事情

public Type GetNullable(Type type)
{
if (type == typeof(Nullable<>))
return type.GetType();

if(type == typeof(int))
type = typeof(int?);
else if(type == typeof(bool))
type = typeof(bool?);
else if(type == typeof(float))
type = typeof(float?);
// etc. you will have to build out every type you want.

return type;
}

public Expression<Func<VwAssignmentActivities, bool>> GetIsNullExpressionEquals(string propName, Type value)
{
var item = Expression.Parameter(typeof(VwAssignmentActivities), "item");
var prop = Expression.Convert(Expression.Property(item, propName), GetNullable(value));

Expression body = Expression.Equal(prop, Expression.Constant(null, prop.Type));

return Expression.Lambda<Func<VwAssignmentActivities, bool>>(body, item);
}

关于c# - LINQ 动态查询生成 'where AssignedUser is null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27507810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com