Solved

Specified Cast is not valid

Posted on 2011-02-24
11
791 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
  • 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
 
LVL 62

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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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 62

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

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…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

920 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now