我有一个通用的网格视图列筛选方法,该方法使用ColumnName和SearchText筛选网格视图记录。这里,当我对可为null的int datacolumn进行操作时,会从该方法引发错误,如:
类型为"System。Int32不能用于"System"类型的参数。方法"Boolean Equals(System.Object)"的"Object"
我的方法代码是:
public static IQueryable<T> FilterForColumn<T>(this IQueryable<T> queryable, string colName, string searchText)
{
if (colName != null && searchText != null)
{
var parameter = Expression.Parameter(typeof(T), "m");
var propertyExpression = Expression.Property(parameter, colName);
System.Linq.Expressions.ConstantExpression searchExpression = null;
System.Reflection.MethodInfo containsMethod = null;
// this must be of type Expression to accept different type of expressions
// i.e. BinaryExpression, MethodCallExpression, ...
System.Linq.Expressions.Expression body = null;
Expression ex1 = null;
Expression ex2 = null;
switch (colName)
{
case "JobID":
case "status_id":
Int32 _int = Convert.ToInt32(searchText);
searchExpression = Expression.Constant(_int);
containsMethod = typeof(Int32).GetMethod("Equals", new[] { typeof(Int32) });
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
case "group_id":
Int32? _int1 = Convert.ToInt32(searchText);
searchExpression = Expression.Constant(_int1);
containsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
//Error throws from this line
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
case "FileSize":
case "TotalFileSize":
Int64? _int2 = Convert.ToInt64(searchText);
searchExpression = Expression.Constant(_int2);
containsMethod = typeof(Int64?).GetMethod("Equals", new[] { typeof(Int64?) });
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
// section for DateTime? properties
case "PublishDate":
case "Birth_date":
case "Anniversary_date":
case "Profile_Updated_datetime":
case "CompletedOn":
DateTime currentDate = DateTime.ParseExact(searchText, "dd/MM/yyyy", null);
DateTime nextDate = currentDate.AddDays(1);
ex1 = Expression.GreaterThanOrEqual(propertyExpression, Expression.Constant(currentDate, typeof(DateTime?)));
ex2 = Expression.LessThan(propertyExpression, Expression.Constant(nextDate, typeof(DateTime?)));
body = Expression.AndAlso(ex1, ex2);
break;
// section for DateTime properties
case "Created_datetime":
case "Reminder_Date":
case "News_date":
case "thought_date":
case "SubscriptionDateTime":
case "Register_datetime":
case "CreatedOn":
DateTime currentDate1 = DateTime.ParseExact(searchText, "dd/MM/yyyy", null);
DateTime nextDate1 = currentDate1.AddDays(1);
ex1 = Expression.GreaterThanOrEqual(propertyExpression, Expression.Constant(currentDate1));
ex2 = Expression.LessThan(propertyExpression, Expression.Constant(nextDate1));
body = Expression.AndAlso(ex1, ex2);
break;
default:
searchExpression = Expression.Constant(searchText);
containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
}
var predicate = Expression.Lambda<Func<T, bool>>(body, new[] { parameter });
return queryable.Where(predicate);
}
else
{
return queryable;
}
}
这是我提出的问题:
var query = Helper.GetUsers().Where(u => u.Id != user_id).OrderByDescending(u => u.Register_datetime).Select(u => new
{
Id = u.Id,
Name = u.First_name + " " + u.Last_name,
IsActive = u.IsActive,
IsVerified = u.IsVerified,
Username = u.Username,
password = u.password,
Birth_date = u.Birth_date,
Anniversary_date = u.Anniversary_date,
status_id = u.status_id,
group_id = u.group_id,
Profile_Updated_datetime = u.Profile_Updated_datetime,
Register_datetime = u.Register_datetime
}).FilterForColumn(ColumnName, SearchText).ToList();
在这里我包括了我的疑问。GetType()。ToString()结果可以更好地理解我对其进行操作的列的类型。
System.Collections.Generic.List`1[<>f__AnonymousType0`12[System.Int32,System.String,System.Boolean,System.Boolean,System.String,System.String,System.Nullable`1[System.DateTime],System.Nullable`1[System.DateTime],System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.DateTime],System.DateTime]]
编辑
找到了此问题的解决方案。在调用Equals(object)
方法之前,需要将表达式转换为Object
:
var converted = Expression.Convert(searchExpression, typeof(object));
body = Expression.Call(propertyExpression, containsMethod, converted);
Nicodems13提出的将searchExpression
的类型显式设置为Object
的建议也应该起作用。
原始
我还没有发现这个问题,但我已经使用Linqpad:在SSCCE中复制了这个问题
void Main()
{
var myInstance = new myClass();
var equalsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
int? nullableInt = 1;
var nullableIntExpr = System.Linq.Expressions.Expression.Constant(nullableInt);
var myInstanceExpr = System.Linq.Expressions.Expression.Constant(myInstance);
var propertyExpr = System.Linq.Expressions.Expression.Property(myInstanceExpr, "MyProperty");
var result = Expression.Call(propertyExpr,equalsMethod,nullableIntExpr); // This line throws the exception.
Console.WriteLine(result);
}
class myClass{public int? MyProperty{get;set;}}
此行:
containsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
返回方法CCD_ 6的CCD_。请注意,参数类型是object
,而不是您所期望的Int32
(或Int32?
)。
原因是typeof(Int32?)
是System.Nullable<Int32>
,它只有Equals(object)
方法。
在LinqPad中玩这个游戏,我认为问题出在:
searchExpression = Expression.Constant(_int1);
当你打电话时:
containsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
您试图调用的Equals
方法是object.Equals(object)
,编译器会告诉您类型int?
不是该方法所期望的类型object
。
最简单的修复方法(尽管我不确定整个代码是否能工作,尽管这个特定的错误会消失)是将您调用的Expression.Constant
的重载更改为指定Equals
期望的类型的重载:
searchExpression = Expression.Constant(_int1, typeof(object));
这将进行编译——不过,有几点需要注意。
-
您的原始
Expression.Constant(_int1)
会生成一个ConstantExpression
,其中Type
为int
,而不是int?
。如果需要的话,您需要指定可为null的类型(Expression.Constant(_int1, typeof(int?))
)。但是,无论如何,您都需要将其强制转换为object
,如上所述。 -
指定
containsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
无论如何都不应该起作用,因为没有这样的方法int?.Equals(int?)
,Equals
方法是System.Object
类上的方法的重写,该类接受object
参数,是问题的根源。您也可以使用:typeof(object).GetMethod("Equals", new[] { typeof(object) });
,因为这是正确的声明。
正如我所说,它应该使用object
进行编译,我不确定代码是否符合您的预期,但我认为是这样。我期待着看到它是否有效:)