Results 1 to 2 of 2
  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2018

    Specific cast is not valid in linq query when compare two tables

    Specific cast is not valid in linq query when compare two tables

    Error display in linq query "specific cast is not valid" at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value) at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)

    LinqQuery give error

    var query1 = (from x in table1.AsEnumerable()
    join y in table2.AsEnumerable() on x.Field<int>("UnitCode") equals y.Field<int>("UnitCode")
    where y.Field<decimal>("CurrentMeterReading") > x.Field<decimal>("CurrentMeterReading")
    select new { UnitCode = x.Field<int>("UnitCode"), CurrentReading = x.Field<decimal>("CurrentMeterReading") }).ToList();


    When make debug the first data table tableReadingExcelsheet retrieve data from excel sheet .

    second datatable readingfromInvoiceTablesql retrieve data from wahinvoice table in sql .

    I need to get list of rows in excel sheet that have current reading less than

    currentreading in wahinvoice table for same UnitCode then display in datagridview .

    Name:  wrong linq query.jpg
    Views: 94
    Size:  20.4 KB

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Sydney, Australia

    Re: Specific cast is not valid in linq query when compare two tables

    Your screenshot inside a code box is clearly useless. Also, please don't bold an entire post. It just makes it harder to read. Bold is intended for emphasis and thus should be used sparingly. The default font is the default for a reason.

    As for the issue, have you examined both of those DataTables to make sure that every record has an 'int' value in the UnitCode column and a 'decimal' value in the CurrentMeterReading column? My first guess would be that at least one row contains NULL in one of those columns, although I'm not sure that I'd have expected that specific error message in that case. The other possibility is that one of the columns doesn't contain the specified data type at all, e.g. UnitCode contains 'string' values rather than 'int'.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.