Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Specified Cast is not valid

Posted on 2011-02-24
11
Medium Priority
?
804 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 400 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 400 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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
LVL 64

Assisted Solution

by:Fernando Soto
Fernando Soto earned 400 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 400 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 64

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 400 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

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

810 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