Search code examples
c#entity-frameworkentity-framework-4

The type of one of the primary key values did not match the type defined in the entity. See inner exception for details


I have the followng method:-

public ActionResult CustomersDetails(string[] SelectRight)
{
    var selectedCustomers = new SelectedCustomers
    {
        Info = SelectRight.Select(GetAccount)
    };

    return View(selectedCustomers);
}

private AccountDefinition GetAccount(string id)
{
    return entities.AccountDefinition.Find(id);
}

but it is returning the following error:-

The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.

On the return entities.AccountDefinition.Find(id); line

So what is causing this error?

The inner exception is:-

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.
Parameter name: keyValues
  Source=EntityFramework
  ParamName=keyValues
  StackTrace:
       at System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues)
       at System.Data.Entity.DbSet`1.Find(Object[] keyValues)

  InnerException: System.Data.EntitySqlException
       HResult=-2146232006
       Message=The argument types 'Edm.Int64' and 'Edm.String' are incompatible for this operation. Near WHERE predicate, line 1, column 90.
       Source=System.Data.Entity
       Column=90
       ErrorContext=WHERE predicate, line 1, column 90
       ErrorDescription=The argument types 'Edm.Int64' and 'Edm.String' are incompatible for this operation.
       Line=1

Solution

  • Look at the exception message The argument types 'Edm.Int64' and 'Edm.String' are incompatible for this operation. Near WHERE predicate, line 1, column 90..

    This implies that the ID of your AccountDefinition class is a long or Int64 however you are trying to query it using a string.

    You need to do one of the following:

    1. Change string[] in CustomersDetails(string[] SelectRight) to long[] and string in GetAccount(string id) to long id
    2. Change return entities.AccountDefinition.Find(id); to return entities.AccountDefinition.Find(long.Parse(id));

    Option 1 is the better option but will require more change (which I would recommend you do), Option 2 is less change but has the possibility it will blow up if id is null or a value which cannot be parsed to a long.