LinqDataSource SessionParameter运算符'=='与操作数类型'Int32'和'Object'不兼容 [英] LinqDataSource SessionParameter Operator '==' incompatible with operand types 'Int32' and 'Object'

查看:357
本文介绍了LinqDataSource SessionParameter运算符'=='与操作数类型'Int32'和'Object'不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在web.config中设置了<sessionState mode="InProc" timeout="1800"> </sessionState>.
在Login.aspx上:

I set <sessionState mode="InProc" timeout="1800"> </sessionState> in web.config.
On Login.aspx:

protected void Button1_Click(object sender, EventArgs e)
  {
      Session["UserID"] = TextBox1.Text;
      Response.Redirect("EditJob.aspx");
  }



在我的错误EditJob.aspx上:



On my Error EditJob.aspx:

<asp:LinqDataSource ID="LinqDataSourceMaster" runat="server"
    ContextTypeName="JobPostDataContext" EntityTypeName="" Select="new (JobID, JobTitle, UserID)"
    TableName="JobLists" Where="UserID == @UserID">
    <WhereParameters>
        <asp:SessionParameter DefaultValue="0" Name="UserID" SessionField="UserID"
            Type="Int32" />
    </WhereParameters>

</asp:LinqDataSource>



我还尝试了EditJob.aspx:



I also tried on EditJob.aspx:

 <asp:LinqDataSource ID="LinqDataSourceMaster" runat="server"
        ContextTypeName="JobPostDataContext" EntityTypeName="" Select="new (JobID, JobTitle, UserID)"
        TableName="JobLists" Where="UserID == @UserID"
        onselecting="LinqDataSourceMaster_Selecting">
        <WhereParameters>
            <asp:SessionParameter DefaultValue="0" Name="UserID" SessionField="UserID"
                Type="Int32" />
        </WhereParameters>

    </asp:LinqDataSource>
public partial class EditJob : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void LinqDataSourceMaster_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        foreach (KeyValuePair<string, object> kvp
        in e.WhereParameters)
        {
            if (kvp.Value == null)
            {
                e.Cancel = true; return;
            }
        }
    }



但它仍然显示.

运算符"=="与操作数类型"Int32"和"Object"不兼容
说明:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪,以获取有关错误及其在代码中起源的详细信息.

异常详细信息:System.Web.Query.Dynamic.ParseException:运算符"=="与操作数类型"Int32"和"Object"不兼容




But it still shows.

Operator ''=='' incompatible with operand types ''Int32'' and ''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.Web.Query.Dynamic.ParseException: Operator ''=='' incompatible with operand types ''Int32'' and ''Object''


How to solve this problem?

推荐答案

int不是可空类型.如果kvp.Value代表int,请尝试将比较更改为此:

An int isn''t a nullable type. if kvp.Value represents an int, try changing the comparison to this:

if (kvp.Value == 0)
{
    e.Cancel = true; return;
}


Prerequisite: LinqDataSource & SqlDataSource Master/Details

When working with the LinqDataSource, you may get the exceptions listed below.

1. Operator '==' incompatible with operand types 'Int32' and 'Object'

The exception occurs because anytime a ControlParameter in the WhereParameters collection (IDictionary<string, object>) is null, it gets treated as type Object causing the LINQ dynamic expression parser comparison to fail. Consider the code snippet below:

 <pre>   <asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="DataClassesDataContext"

        Select="new (OrderID, ProductID, UnitPrice, Quantity, Discount, Order)" TableName="Order_Details"

        Where="OrderID == @OrderID">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="OrderID" PropertyName="SelectedValue"

                Type="Int32" />
        </WhereParameters>
    </asp:LinqDataSource>


这是经典Master/Details场景的一部分,在该场景中,LinqDataSource根据在GridView1中选择的OrderID获取订单明细.

当页面第一次加载时,OrderID ControlParameter等于GridView1.SelectedValue. GridView1.SelectedValue为null,因为尚未在GridView1中选择任何记录.不幸的是,LinqDataSource仍然尝试获取数据. Linq表达式解析器将null参数视为Object类型,并且比较失败,因为它期望使用Int32类型.

我们需要的是一种防止在任何参数为null时发生Select的方法.由于某些原因,与SqlDataSource不同,LinqDataSource不具有CancelSelectOnNullParameter属性.当设置为true时,此属性将在SelectParameters集合中的任何参数为null时取消选择.

我们可以通过处理LinqDataSource的Selecting事件并在任何WhereParameter为null的情况下调用Cancel方法来实现此目标,如下所示:


This is part of the classic Master/Details scenario where the LinqDataSource fetches the Order Details based on the OrderID selected in the GridView1.

When the page loads the first time, the OrderID ControlParameter is equal to GridView1.SelectedValue. GridView1.SelectedValue is null since no record has been selected in the GridView1 yet. Unfortunately, the LinqDataSource still attempts to fetch the data. The Linq expression parser treats the null parameter as type Object and the comparison fails because it was expecting type Int32.

What we need here is a way to prevent the Select from occurring when any parameter is null. The LinqDataSource, unlike the SqlDataSource, for some reason, does not have a CancelSelectOnNullParameter property. This property when set to true, will cancel the select when any parameter in the SelectParameters collection is null.

We can implement this by handling the Selecting event of the LinqDataSource and call the Cancel method when any WhereParameter is null like so:

protected void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
   {
       foreach (KeyValuePair<string, object> kvp in e.WhereParameters)
       {
           if (kvp.Value == null)
           {
               e.Cancel = true;
               return;
           }
       }
   }




2.运算符"=="与操作数类型"Guid"和"String"不兼容

如果WhereParameters集合中的参数类型为Guid,则会发生此异常.




2. Operator ''=='' incompatible with operand types ''Guid'' and ''String''

This exception occurs in cases where a parameter in the WhereParameters collection is of type Guid.

<asp:LinqDataSource ID="LinqDataSource2" runat="server"
       ContextTypeName="DataClassesDataContext"
       Select="new (DummyID, FirstName, LastName)" TableName="DummyTables"
       Where="DummyID == @DummyID" onselecting="LinqDataSource2_Selecting">
       <WhereParameters>
           <asp:ControlParameter ControlID="GridView1" Name="DummyID"
               PropertyName="SelectedValue" Type="Object" />
       </WhereParameters>
   </asp:LinqDataSource>


在上面的代码段中,您可以看到GridView1.SelectedValue被定义为LinqDataSource的WhereParameter. DummyID是GridView1中数据的主键,类型为Guid.在ControlParameter中,将其Type设置为Object,因为在TypeCode枚举中不提供Guid.不幸的是,这导致linq表达式解析器将值视为String类型,导致比较失败.

根据Dynamic Expression API(LinqDataSource内部使用了一种味道),我们可以使用语法type(expr)进行显式转换,其中type是类型名称(可选),其后是?.而expr是一个表达式.表达式语言定义了以下原始类型:

对象布尔型Char字符串SByte字节
Int16 UInt16 Int32 UInt32 Int64 UInt64
十进制单精度Double DateTime TimeSpan Guid

基本类型与.NET Framework基本类库的System命名空间中类似命名的类型相对应.您还可以通过编写?使用值类型的可为空的形式.类型名称之后(例如:Where ="Foo = Int32?(@ Foo)").

因此,我们可以像这样重写where子句,从而摆脱了异常.


In the snippet above, you can see that the GridView1.SelectedValue is defined as a WhereParameter for the LinqDataSource. DummyID is the primary key of the data in GridView1 and is of type Guid. In the ControlParameter, its Type is set to Object because Guid is not available in the TypeCode enum. Unfortunately, this results in the linq expression parser treating the value as type String causing the comparison to fail.

According to the Dynamic Expression API, a flavor of which is used by the LinqDataSource internally, we can perform explicit conversions using the syntax type(expr) where type is a type name optionally followed by ? and expr is an expression. The expression language defines the following primitive types:

Object Boolean Char String SByte Byte
Int16 UInt16 Int32 UInt32 Int64 UInt64
Decimal Single Double DateTime TimeSpan Guid

The primitive types correspond to the similarly named types in the System namespace of the .NET Framework Base Class Library. You can also use the nullable form of a value type by writing a ? after the type name (ex: Where="Foo = Int32?(@Foo)").

Therefore, we can rewrite our where clause like so which gets rid of the exception.

<asp:LinqDataSource ID="LinqDataSource2" runat="server"
      ContextTypeName="DataClassesDataContext"
      Select="new (DummyID, FirstName, LastName)" TableName="DummyTables"
      Where="DummyID == Guid(@DummyID)" onselecting="LinqDataSource2_Selecting">
      <WhereParameters>
          <asp:ControlParameter ControlID="GridView1" Name="DummyID"
              PropertyName="SelectedValue" Type="Object" />
      </WhereParameters>
  </asp:LinqDataSource>


IMO,如果LinqDataSource具有CancelSelectOnNullParameter且TypeCode枚举包括上面列出的原始类型和可为空的值类型,则可以避免这些异常以及其他一些异常.


IMO, both these exceptions and a couple of others could probably be avoided if the LinqDataSource had a CancelSelectOnNullParameter and if the TypeCode enum had included the primitive types listed above and nullable value types.


这篇关于LinqDataSource SessionParameter运算符'=='与操作数类型'Int32'和'Object'不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆