In my case the error was: "The specified cast from a materialized 'System.Int64' type to a nullable 'System.Int32' type is not valid", and the cause of the error was that I have an SQL Server view mapped with EF, which declares an int column that is filled with the return value of the SQL Server function ROW_NUMBER(), which return type is bigint.
Tweaking the view column to bigint type fixed the issue.