mvc4表达式树包含整数

时间:2015-03-15 13:06:54

标签: entity-framework asp.net-mvc-4 contains expression-trees sql-like

我想为整数实现表达式树,如下面的查询:

Select * From TableName Where PKID In (1,2,3,4,5)

相关的提取代码:

protected Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue, string propertyType)
{
    var parameter = Expression.Parameter(typeof(T), "type");
    switch (propertyType)
    {
        case "string":
        case "string?":
            var stringProperty = Expression.Property(parameter, propertyName);
            var stringValue = Expression.Constant(propertyValue.Trim(), typeof(string));
            MethodInfo stringMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            var stringContainsMethod = Expression.Call(stringProperty, stringMethod, stringValue);
            return Expression.Lambda<Func<T, bool>>(stringContainsMethod, parameter);

        case "int?":
            var intProperty = Expression.Property(parameter, propertyName);
            var intValues = Expression.Constant(propertyValue.Trim(), typeof(string));
            MethodInfo intMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
            var intContainsMethod = Expression.Call(intProperty, intMethod, intValues); // this line gives error
            return Expression.Lambda<Func<T, bool>>(intContainsMethod, parameter);
    }
}

// Calling above function for string works. Products is a table in Database and Entity framework generated the class based on database first.
var filterLambda = GetExpression<Products>("ProductName", "chicken", "string?"); // No error here, works great

// Calling above function for int gives error
var filterLambda = GetExpression<Products>("ProductId", "1,2,3,4,5", "int?"); // Error here

我收到错误:

  

方法&#39;布尔包含(System.String)&#39;声明类型&#39; System.String&#39;不能使用类型&System; System.Int32&#39;

的实例调用

当然很清楚,ProductId列是整数,值是字符串。整数没有包含所以我认为我应该使用字符串包含方法。请任何人告诉我如何解决这个问题?

0 个答案:

没有答案