Solved

Specified Cast is not valid

Posted on 2011-02-24
11
800 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

729 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