LINQ Dynamic QUERY生成'where AssignedUser is null'

4c8rllxm  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(107)

我正在尝试构建动态表达式查询,以便只获取列中包含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);
}

任何帮助感激

puruo6ea

puruo6ea1#

你得到的错误是因为你在你的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);
}

相关问题