Entity framework "InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Decimal."


Question: I have spend so much time on this error but I don't see where the issue is: I have double checked both the Modal (C# POCO) and the Database Table to make sure all the Data Types are the same. The error keeps on saying: "InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Decimal."

How do you resolve this issue? Am I missing something or not?

 

Solution: Look very carefully, I repeat: Look very carefully in your POCO or Data Model. There is a big chance that you forgot to type Int on the Property instead you typed decimal. 99 % the Compiler is right, there is an issue. It is up to you to find what property is throwing an error.

[Note]: Another way to solve for this error is by finding out what Property is actually causing that error. Sometimes Entity Framework does not throw detailed Error Message, hence you can't find out what property or column (from Database Perspective) actually had an error converting from an Integer to a Decimal.

One way to get a Detailed Error Message or Detailed Logs in your console when debugging EF Core 6 is by including the following code in the DatabaseContext Class.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){

if(!optionsBuilder.IsConfigured){
optionsBuilder.UserSqlServer(Configuration.GetConnectionString("TheNameOfConnectionStringFromAppSettings.json"))
//Add the following code to enable detailed logging
.EnableSensitiveDataLogging()
.EnableDetailedErrors(); //Good Luck Debugging :)
}
}





© 2024 - ErnesTech - Privacy
E-Commerce Return Policy