【问题标题】:Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types无法将类型“System.Int32”转换为类型“System.Object”。 LINQ to Entities 仅支持转换实体数据模型基元类型
【发布时间】:2011-04-06 18:49:41
【问题描述】:

我正在使用 LINQ to Entities,但在运行时出现以下错误。 “无法将类型 'System.Int32' 转换为类型 'System.Object'。LINQ to Entities 仅支持转换实体数据模型原始类型”。

LINQ 语句如下所示:

(From item In _EntityObject.SystemUsers
 Where item.Username = UsernameValue And
     Not Equals(item.ID, IDValue)
 Select item.Active).Count

当 IDValue 设置为 Nothing 时,查询会完美执行,而当我将值设置为 Integer 时,会出现上述错误。 item.ID 是 Integer 类型的属性,而 IDValueNullable(Of Integer) 类型的属性。

我有相同的 LINQ 查询,我在其他地方使用的不同字段运行良好。

(From item In _EntityObject.Languages
 Where item.Reference = Reference And
     Not Equals(item.ID, ID)
 Select item.Name).Count

【问题讨论】:

    标签: asp.net linq linq-to-entities primitive-types


    【解决方案1】:

    只需使用= 符号

    (From item In _EntityObject.SystemUsers
     Where item.Username = UsernameValue And
         Not (item.ID = IDValue)
     Select item.Active).Count
    

    【讨论】:

    • 感谢您的快速回复。但是 IDValue 的值可以是 Nothing (NULL),这种平等比较不起作用。
    • 在这种情况下使用 (Not (m.CountryEnumId = IDValue)) 或 (IDValue Is Nothing),但由于您的 item.ID 永远不会是 Nothing,因此省略 where 子句部分
    • 感谢您的帮助...您为我指明了正确的方向。实际上,ID 可能是 Nothing。最终查询如下:From item In _EntityObject.SystemUsers Where item.Username = Username And (Not (item.ID = IDValue) Or IDValue Is Nothing) Select item.Name).Count
    【解决方案2】:

    问题通过以下语句解决:

    (From item In _EntityObject.SystemUsers Where 
    item.Username = Username And (Not (item.ID = IDValue)
     Or IDValue Is Nothing) Select item.Name).Count)
    

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多