Solved

Specified Cast is not valid

Posted on 2011-02-24
11
799 Views
Last Modified: 2013-12-17
I am running a LINQ query against a database.  The program had been working in the past but recenctly it started to give me this error when the LINQ query is run.  Can someone point me in the right direction where I need to look to resolve this problem.  Here is the code it is hanging on.


 var provtbl = from prov in dcABC.PROVIDERs
                                      where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
                                      select new { prov };


                        if (provtbl.Count() == 0)
                        {
                            // No Record found in Practice Table
                           
                        }
                        else
                        {
                            foreach (var provrec in provtbl)-----------<<<<<---------  Error Occurs Here
                            {
                                // Found Practice Record
                                //string LoginUser;
                               
                                physicianNPI = provrec.prov.PHYSICIAN_NPI;
0
Comment
Question by:kwh3856
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +3
11 Comments
 

Accepted Solution

by:
vultre earned 100 total points
ID: 34971264
Hello kwh3856,

As far as I know, there is no enumarable object for loop, therefore you should use it as :

var provtbl = from prov in dcABC.PROVIDERs
                                      where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
                                      select prov;

   if (provtbl.Count() == 0)
                        {
                            // No Record found in Practice Table
                           
                        }
                        else
                        {
                            foreach (var provrec in provtbl)
                            {
                                // your logic codes bla bla...
                               
                           }
                      }

As that, it will work, I think.

Thank you.
0
 
LVL 19

Assisted Solution

by:Bardobrave
Bardobrave earned 100 total points
ID: 34971269
Have you tried to assign types to provtbl and provrec instead of using undeterminate variables?
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34971273
Hmm, at first glance that looks like it should work - does the exception say specifically what type it's trying to cast from and to?  Is the identifier "provrec" used earlier in the code?  Can you post the rest of the foreach loop?
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 63

Assisted Solution

by:Fernando Soto
Fernando Soto earned 100 total points
ID: 34971275
Hi Kenny;

From the looks of the code provided that should work. It may be that one of the code files which have not been updated could have a problem or is corrupted. Please try this, from the main menu in the IDE click on Build -> Clean Solution then recompile the code and see if the error is still there.

On another point this part of the query, select new { prov }, creates an anonymous type. When you use the keyword new as you did it will create a anonymous type. In this case you could return a concrete type of PROVIDERs by dropping  the new keyword and the { }. changing the code as follows:

var provtbl = from prov in dcABC.PROVIDERs
              where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
              select prov;


if (provtbl.Count() == 0)
{
    // No Record found in Practice Table
   
}
else
{
    foreach (var provrec in provtbl)-----------<<<<<---------  Error Occurs Here
    {
        // Found Practice Record
        //string LoginUser;
       
        physicianNPI = provrec.PHYSICIAN_NPI;

Open in new window


Please not the changes in the foreach loop as well.

Fernando
0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 100 total points
ID: 34971332
I think what vultre's getting at is that in your LINQ query there's no need to use "select new { some value }" (that's useful for returning a completely new type, but all it seems you want to do is return a provider).

So, instead of
var provtbl = from prov in dcABC.PROVIDERs
                     where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
                     select new { prov };

foreach (var provrec in provtbl)-----------<<<<<---------  Error Occurs Here
{
    // Found Practice Record
    //string LoginUser;
                                
    physicianNPI = provrec.prov.PHYSICIAN_NPI; 

Open in new window


You can use
var provtbl = from prov in dcABC.PROVIDERs
                     where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
                     select prov;

foreach (var provrec in provtbl)-----------<<<<<---------  Error Occurs Here
{
    // Found Practice Record
    //string LoginUser;
                                
    physicianNPI = provrec.PHYSICIAN_NPI; 

Open in new window


Although I think this is unrelated to your problem.
0
 

Author Comment

by:kwh3856
ID: 34971659
Ok...I did not quite understand what the new keyword meant so I have taken it out as you have suggested.  I also did a clean new.  Still no luck.  I just set a breakpoint at the

var provtbl = from prov in dcABC.PROVIDERs
                                      where prov.PRACTICE_TIN == userrec.u.PRACTICE_TIN
                                      select prov;

I then hovered over the provtble and told it to display results.  It gave me the invalid cast error.  I waited about 20 seconds and then did the same thing.  It then displayed the record for the table.....but....some fields showed as NULL when there is actually data in the SQL table.  Any thoughts?


0
 

Author Comment

by:kwh3856
ID: 34971673
now as I step through the code one line at a time, it let me by and continured executing.  It seems to be some kind of delay problem with the SQL server not responding in time.  Does that make sense?
0
 

Author Comment

by:kwh3856
ID: 34971714
additionally, I am now seeing the same error in a completely different area of the program in a different table.


Here is the code where I get the same error message.


var EncounterMasterResult = from encountermasterdata in dcABC.EncounterMasters
                                        where encountermasterdata.MPI == ConvertedMPI
                                        orderby encountermasterdata.EncDate

                                        select new
                                        {
                                            encountermasterdata.ChiefComplaint,
                                            encountermasterdata.CRencounterId,
                                            encountermasterdata.EncDate,
                                            encountermasterdata.HPINotes,
                                            encountermasterdata.NPI,


                                        };

            int clinicalencdataCount = EncounterMasterResult.Count();    // <===== Added this line to get total count here

            if (clinicalencdataCount == 0)                    // <===== Changed this line so that the query does not get executed again
            {
                // No user record found
            }
            else
            {

                // Set the grid to the data source
                this.UltraWebGrid1.DataSource = EncounterMasterResult;
                this.UltraWebGrid1.DisplayLayout.Bands.Clear();
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 34971835
Hi Kenny;

What happens if you change the query to this:

var EncounterMasterResult = (from encountermasterdata in dcABC.EncounterMasters
                             where encountermasterdata.MPI == ConvertedMPI
                             orderby encountermasterdata.EncDate
                             select new
                             {
                                 encountermasterdata.ChiefComplaint,
                                 encountermasterdata.CRencounterId,
                                 encountermasterdata.EncDate,
                                 encountermasterdata.HPINotes,
                                 encountermasterdata.NPI,
                             }).ToList();

Open in new window


Fernando
0
 
LVL 10

Assisted Solution

by:John Claes
John Claes earned 100 total points
ID: 34971861
It looks like you're right .
Linq only executes the real select when starting the Foreach-Loop
If the call is timing-out the IQuerable<T> null cant cast the null part to a T-Object.

You might look at creating a Index upon the Field : prov.PRACTICE_TIN
This might help you alot.

regards

poor beggar
0
 

Author Closing Comment

by:kwh3856
ID: 34976625
Thank you each for your expert advice.  I finally found the problem.  I had the same field in two different tables that was not the same type.  I awarded each of you points because I learned from each of your comments and now have a better understanding of LINQ.
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Securing WEBAPI on Azure 2 54
Activating .NET Framework 3.5 and which option to choose 5 53
Run tasks synchronously in background thread 19 78
Convert VB web project to C# 3 60
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question