I am trying build dynamic expression query to get only rows which has null in the column
where AssignedUser is null
, below is my code, but it is not doing what i expected. Can any one spread the light on the issue please?
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);
}
Any help appreciated
The error you are getting is because you have a value in your Nullable. The get type returns Int32 even though the variable is a Nullable. Then you are trying to convert the null to int.
Assuming you only care about finding null values, I would do something like this
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);
}