[SOLVED!! Entity Framework Error Asp.Net Core 3.1] InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`


Question: How do you resolve the Entity Framework Error that says, InvalidCastException: Unable to cast object of type 
Microsoft EntityFrameworkCore Query Internal EntityQueryable

System Threading Tasks.Task 1[System Collections Generic IEnumerable]

'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[ClassName]' to type 'System.Threading.Tasks.Task`1[System.Collections.Generic.IEnumerable`1[ClassName]]'

 

Solution: When this error happens, chances are that you have created a function in the Repository Class without specifying the function as "async" and/or you might have attempted to cast the whole result set from the database into an IEnumerable because that is what the IntelliSense recommended you.

  • In order to resolve this error, add an "async" to the function, and remove the casting in front of the results set you are returning to the caller. This way the result that is returned from the function is of a Task, which means it will run on another Thread, leaving the Main Thread Safe for UI Processing.

    [Note] If this solution helped you, leave a comment so that other Developers can find it useful.





© 2024 - ErnesTech - Privacy
E-Commerce Return Policy