0

It's been a while since I am trying to figure out what is causing a cast exception in this case. Following is my code.

var ratingTermDetails = dtRating.AsEnumerable()
    .Where(data => data.Field<int>("RATINGID") == ratingId)
    .FirstOrDefault();

dtRating is a datatable which gets populated from the database (oracle). The datatype of the column Ratingid is Integer in the database and the column is not nullable. The variable ratingId is an integer too.

juharr
  • 31,741
  • 4
  • 58
  • 93
  • 2
    Whats the exception? – Fruchtzwerg May 01 '20 at 13:34
  • 1
    possibly a `null` in one of the cells? and: what does the `dtRating` think the column type is? It might have become `long` when fetching from Oracle – Marc Gravell May 01 '20 at 13:34
  • 1
    Can the column RatingId in the database be NULL? – José Amílcar Casimiro May 01 '20 at 13:35
  • No. It is a primary key field and not nullable. – Ashish Samant May 01 '20 at 13:38
  • 3
    then: please look at `dtRating.Columns["RATINGID"].DataType` - what is it? (also: *why* use `DataTable` here? the number of places where `DataTable` is the appropriate solution is very minimal) – Marc Gravell May 01 '20 at 13:43
  • @Fruchtzwerg Specified cast is not valid. (InvalidCastException) – Ashish Samant May 01 '20 at 13:43
  • @MarcGravell You're right. The type that is getting returned is a decimal. I don't understand how though? I've usually used SQL server throughout and this is my first time using Oracle. Do Integers in oracle translate to decimals in C#? Also, if you wish, please write this as an answer. Your solution fixed my issue. Thanks a lot for your time. – Ashish Samant May 01 '20 at 13:57
  • Just to follow along with @MarcGravell's comment. DataTables were the right thing to use in 2003. Take a look at something like Dapper or EF - working with collections of typed objects is so much more 2020 than datatables – Flydog57 May 01 '20 at 14:01

2 Answers2

0

I don't know how much help this is because I've never seen similar Linq before. But in my understanding, you're saying that RATINGID is int in the DB and it's a primary key?

Then this should work.

var ratingTermDetails = dtRating
    .Where(data => data.Field.RATINGID == ratingId)
    .FirstOrDefault();
Aram Yako
  • 41
  • 1
  • 5
0

As @MarcGravell said, the variable was getting converted into System.Decimal in C#. Upon changing to my code worked.