繁体   English   中英

类型'System.Int32'的表达式不能用于方法'Boolean Equals(System.Object)'的类型'System.Object'的参数

[英]Expression of type 'System.Int32' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)'

我在使用网格视图列明智搜索工具时遇到一个错误。 在这里我有varchar,int和nullable这样的多列。 我做了一个像FilterColumn这样的辅助方法,它带有两个参数(ColumnName,SearchText)。 现在我在用int值过滤时遇到了一个问题。

这是这种方法:

public static class Helper
{
    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;
            Expression converted = null;
            switch (colName)
            {
                // section for int properties
                case "party_id":
                case "type_id":
                case "status_id":
                case "category_id":  //here problem occurs
                    Int32 _int = Convert.ToInt32(searchText);
                    searchExpression = Expression.Constant(_int);
                    containsMethod = typeof(Int32).GetMethod("Equals", new[] { typeof(Int32) });
                    body = Expression.Call(propertyExpression, containsMethod, searchExpression);
                    break;
                // section for int? properties
                case "country_id":
                case "state_id":
                    Int32? _int1 = Convert.ToInt32(searchText);
                    searchExpression = Expression.Constant(_int1);
                    converted = Expression.Convert(searchExpression, typeof(object));
                    containsMethod = typeof(Int32?).GetMethod("Equals", new[] { typeof(Int32?) });
                    body = Expression.Call(propertyExpression, containsMethod, converted);
                    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_date":
                case "Register_Date":
                    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;
        }
    }
}

这是我的搜索按钮代码,我如何将列值和搜索值传递给FillGrid:

protected void btnsearch_Click(object sender, System.EventArgs e)
    {
        if (DDL_Column_List.SelectedItem.Value.Equals("19"))
        {
            RegularExpressionValidator5.Enabled = true;
        }
      if (Page.IsValid)
        {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                System.Threading.Thread.Sleep(2000);
                if (DDL_Column_List.SelectedItem.Value != "-1" && txtsearch.Text.Trim() != "")
                {
                    switch (DDL_Column_List.SelectedItem.Text.ToString())
                    {
                        case "Name":
                            Session["ColumnName"] = "Name";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Type":
                            Session["ColumnName"] = "type_id";
                            Session["SearchText"] = db.PartyTypes.Where(t => t.typename.Contains(txtsearch.Text.Trim())).Select(t => t.Id).SingleOrDefault().ToString();
                            break;
                        case "Owner Name":
                            Session["ColumnName"] = "Ownername";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Owner Mobile":
                            Session["ColumnName"] = "Ownermob";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Contact Person Name":
                            Session["ColumnName"] = "ContactPerson";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Contact Person Mobile":
                            Session["ColumnName"] = "ContactPersonmob";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Phone":
                            Session["ColumnName"] = "Phone";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Mobile":
                            Session["ColumnName"] = "Mobile";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Room":
                            Session["ColumnName"] = "Room";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Building":
                            Session["ColumnName"] = "Build";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Road":
                            Session["ColumnName"] = "Road";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Area":
                            Session["ColumnName"] = "Area";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "City":
                            Session["ColumnName"] = "City";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Country":
                            Session["ColumnName"] = "country_id";
                            Session["SearchText"] = db.Countries.Where(c => c.Country_name.Equals(txtsearch.Text.Trim())).Select(c => c.Id).SingleOrDefault().ToString();
                            break;
                        case "State":
                            Session["ColumnName"] = "state_id";
                            Session["SearchText"] = db.States.Where(s => s.state_name.Equals(txtsearch.Text.Trim())).Select(s => s.Id).SingleOrDefault().ToString();
                            break;
                        case "Email":
                            Session["ColumnName"] = "Email";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Remark":
                            Session["ColumnName"] = "Remark";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Username":
                            Session["ColumnName"] = "Username";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                        case "Register Date":
                            Session["ColumnName"] = "Register_Date";
                            Session["SearchText"] = txtsearch.Text.Trim();
                            break;
                    }
                }
                else
                {
                    Session["SearchText"] = null;
                    Session["ColumnName"] = null;
                }
                this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByENTYPE"] , (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
                UpdatePanel10.Update();
                MPE.Show();
            }
        }
    }

在这里,当用户输入一些字符串值(例如“客户”)时,使用int值时,我遇到一个问题,然后我必须找出属于该文本的ID,然后将此ID传递给会话,然后使用我的助手方法对其进行过滤。 现在我在type_id的情况下有问题。 这里抛出一个错误:

Server Error in '/CRM' Application.

Expression of type 'System.Int32' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)'

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: Expression of type 'System.Int32' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)'

Source Error: 


Line 42:                     converted = Expression.Convert(searchExpression, typeof(object));
Line 43:                     containsMethod = typeof(Int32).GetMethod("Equals", new[] { typeof(Int32) });
Line 44:                     body = Expression.Call(propertyExpression, containsMethod, searchExpression);
Line 45:                     break;
Line 46:                 case "country_id":

Source File: f:\CRM\App_Code\Helper.cs    Line: 44 

Stack Trace: 


[ArgumentException: Expression of type 'System.Int32' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)']
   System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi) +4189655
   System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection`1& arguments) +132
   System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments) +71
   System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments) +29
   Helper.FilterForColumn(IQueryable`1 queryable, String colName, String searchText) in f:\CRM\App_Code\Helper.cs:44
   Staff_Raise_Ticket.FillGrid(String StartAlpha, Int32 GroupByENTYPE, String ColumnName, String SearchText) in f:\CRM\Staff\Raise_Ticket.aspx.cs:249
   Staff_Raise_Ticket.btnsearch_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:1342
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

而且我不明白这里出了什么问题....

错误中的代码与Helper方法的代码不匹配。 该错误报告此:

    converted = Expression.Convert(searchExpression, typeof(object));
    containsMethod = typeof(Int32).GetMethod("Equals", new[] { typeof(Int32) });
    body = Expression.Call(propertyExpression, containsMethod, searchExpression);
    break;
case "country_id":

当我在代码中搜索case "country_id": ,发现以下case "country_id":行:

case "category_id":  //here problem occurs
    Int32 _int = Convert.ToInt32(searchText);
    searchExpression = Expression.Constant(_int);
    containsMethod = typeof(Int32).GetMethod("Equals", new[] { typeof(Int32) });
    body = Expression.Call(propertyExpression, containsMethod, searchExpression);
    break;
// section for int? properties
case "country_id":

错误报告的第一行代码

converted = Expression.Convert(searchExpression, typeof(object));

不会出现在您发布的代码中,并且很可能是错误的根源:您正在尝试调用一个带有object参数的Int32参数的方法,因为您正在转换searchExpression (它可能已经具有正确的类型, Int32 )键入object 确保您正在查看的代码是正在执行的代码,然后删除对对象的转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM