EF6 - Invalid cast from decimal to int32

c# entity-framework entity-framework-6


I have some table with a field defined like...

[oneField] NUMERIC(2) NULL,

And the corresponding c# entity model...

public int? oneField { get; set; }

Fluent configuration...

Property(r => r.oneField)

Well, with all this above, I'm getting the following exception when retrieving data from the DB..

System.InvalidOperationException: The specified cast from a materialized
  'System.Decimal' type to a nullable 'System.Int32' type is not valid.

Any ideas to fix this? I could understand that if the NUMERIC field would have a decimal part that might cause the problem, but being just an integer value of 2 digits, why cannot be casted into an INT32?

Note: I know that if I change the field in the table to be an INT problem will be solved, but I'd like to keep the NUMERIC(2), as represents better the values that are to be stored there (Numbers with 2 digits).

5/31/2018 9:12:12 AM

Accepted Answer

If you want to use NUMERIC(2) then you need a decimal model property otherwise you will see the conversion errors that you report. So your solution is to change the database or change your model.

However, NUMERIC(2) is overkill for your purpose and will consume 5 bytes where you only want numbers up to 99. Instead you should consider using a TINYINT which will allow you to store numbers from 0 to 255. That would mean the storage is only a single byte and your model could be byte to match.

5/31/2018 9:30:20 AM

Popular Answer

As far as I understand, it tells you that the column was materialized into a System.Decimal object and you're trying to cast it to a System.Int32 object which is not supported. Try using INTEGER to define your database column

Or alternatively using System.Decimal to define your EF object

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow