Search code examples
asp.netlinqlinq-to-entitiesprimitive-types

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types


I am using LINQ to Entities and I am getting the following error at runtime. "Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types".

The LINQ statement look like:

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

When IDValue is set to Nothing, the query executes perfectly while when I set the value to an Integer I'm getting the above error. item.ID is property of type Integer while IDValue is of type Nullable(Of Integer).

I have the same LINQ query which different fields that I am using somewhere else which is working perfectly.

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

Solution

  • Issue solved with the below statement:

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