C# LINQ动态查询生成';其中AssignedUser为null';

C# LINQ动态查询生成';其中AssignedUser为null';,c#,sql,linq,ado.net,expression,C#,Sql,Linq,Ado.net,Expression,我正在尝试构建动态表达式查询,以仅获取列中包含null的行 where AssignedUser is null ,下面是我的代码,但它没有达到我的预期。有谁能把这件事讲清楚吗 private Expression<Func<VwAssignmentActivities, bool>> GetIsNullExpressionEquals<T>(string propName, T value) { var item = Expression.Para

我正在尝试构建动态表达式查询,以仅获取列中包含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);
}
私有表达式GetIsNullExpressionEquals(字符串propName,T值)
{
var item=表达式参数(typeof(VwAssignmentActivities),“item”);
var prop=Expression.Convert(Expression.Property(item,propName),value.GetType());
表达式体=Expression.Equal(prop,Expression.Constant(null,prop.Type));
返回表达式.Lambda(body,item);
}

您得到的错误是因为您的Nullable中有一个值。get类型返回Int32,即使变量是可为null的。然后尝试将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);
}
公共类型GetNullable(类型)
{
if(type==typeof(可为空))
返回类型。GetType();
if(type==typeof(int))
类型=类型(int?);
else if(type==typeof(bool))
类型=类型(bool?);
else if(type==typeof(float))
类型=类型(浮动?);
//等等。你将必须构建出你想要的每一种类型。
返回类型;
}
公共表达式GetIsNullExpressionEquals(字符串propName,类型值)
{       
var item=表达式参数(typeof(VwAssignmentActivities),“item”);
var prop=Expression.Convert(Expression.Property(item,propName),GetNullable(value));
表达式体=Expression.Equal(prop,Expression.Constant(null,prop.Type));
返回表达式.Lambda(body,item);
}

抛出一个错误,因为道具类型为“int”,并退出程序。异常是什么?您可以添加实际的异常吗?下面是来自堆栈的错误消息“参数类型不匹配”是的,我在值中得到了-1,但我没有使用“value”,而是使用null
表达式body=Expression.Equal(道具,表达式.Constant(null,prop.Type))你好,用户3444160,太棒了!您的解决方案在查询中返回了
([Extent1].[AssignedUser]为NULL)
,这是我所期望的。谢谢你抽出时间。圣诞快乐伙伴:)我做了一件事。返回类型。GetType();应为返回类型;