none
InvalidCastException using LINQ - can you see what is wrong?

    Question

  • This bit of code is not working for me:

    public List<Person> GetPersonByLastName(String lastName) 
            { 
                DataClasses1DataContext db = new DataClasses1DataContext(); 
                var matchingPersons = from per in db.Persons 
                                      where per.LastName.StartsWith(lastName) 
                                      select per; 
                return matchingPersons.ToList(); 
            } 


    I get an exception in the last line when trying to convert matchingPersons to a List:

    System.InvalidCastException was unhandled by user code
      Message="Kan ikke bruke objekttypen System.Int32 som System.String."
      Source="System.Data"
      StackTrace:
           ved System.Data.SqlClient.SqlBuffer.get_String()
           ved System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
           ved Read_Person(ObjectMaterializer`1 )
           ved System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
           ved System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
           ved System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
           ved SQLDataWeb.Service1.GetPersonByLastName(String lastName) i C:\Users\stidan\Documents\Visual Studio 2008\Projects\SQLData\SQLDataWeb\Service1.svc.cs:linje 21
           ved SyncInvokeGetPersonByLastName(Object , Object[] , Object[] )
           ved System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
           ved System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
      InnerException:


    I am simply trying to fetch some data from a table that has FirstName and LastName columns (and primary key).

    Any help would be appreciated.

    Stian
    Tuesday, October 14, 2008 7:38 AM

Answers

  • Well, I rebuilt the database and now it works. Don't know what was wrong with the old one, but it now converts the query result to a List no problem.

    Stian
    • Marked as answer by Harry Zhu Thursday, October 16, 2008 6:17 AM
    Wednesday, October 15, 2008 6:36 AM

All replies

  • Hey

    Try this

    return matchingPersons.ToList<List<Person>>(); 

    or

    Try cast the var to list of person

    matchingPersons.Cast<List<Person>>();

    Http://DominatorLegend.Co.Nr
    Tuesday, October 14, 2008 12:13 PM
  • John F. Gouda said:

    Hey


    Try this

    return matchingPersons.ToList<List<Person>>(); 

    or

    Try cast the var to list of person

    matchingPersons.Cast<List<Person>>();

    Http://DominatorLegend.Co.Nr


    Hey john and thanks for your suggestions.

    I keep getting a message that I cannot convert the type System.Collections.Generic.list<SQLDataWeb.Person> to System.Collections.Generic.List<SQLDataWeb.Person>

    Your first suggestion returns:

    Error    1    Instance argument: cannot convert from 'System.Linq.IQueryable<SQLDataWeb.Person>' to 'System.Collections.Generic.IEnumerable<System.Collections.Generic.List<SQLDataWeb.Person>>'    C:\Users\stidan\Documents\Visual Studio 2008\Projects\SQLData\SQLDataWeb\Service1.svc.cs    22    19    SQLDataWeb

    Your second suggestion returns:

    Error    1    Cannot implicitly convert type 'System.Linq.IQueryable<System.Collections.Generic.List<SQLDataWeb.Person>>' to 'System.Collections.Generic.List<SQLDataWeb.Person>'. An explicit conversion exists (are you missing a cast?)    C:\Users\stidan\Documents\Visual Studio 2008\Projects\SQLData\SQLDataWeb\Service1.svc.cs    22    19    SQLDataWeb

    The code I am trying to run is taken from a tutorial on using Silverlight DataGrid through a Data Service. The tutorial is here: http://marlongrech.wordpress.com/2008/03/22/how-can-i-get-the-datagrid-control-for-silverlight-2-beta-1-to-show-up-in-blend/

    The only thing I am doing different from the tutorial is using a different database and different database columns names.

    Any ideas?

    Stian
    Tuesday, October 14, 2008 12:43 PM
  • I've tried some more stuff with this code and have now simplified my question a bit.

    This is the code that I am trying to run now:

    DataClasses1DataContext db = new DataClasses1DataContext(); 
     
    var matchingPersons = from per in db.Persons 
            select per; 
     
    List<Person> P = matchingPersons.ToList<Person>(); 

    I get the following error on the last line:

    Cannot use the object type System.Int32 as System.String.

    It is trying to convert a System.Int32 to a System.String for some reason and I get an InvalidCastException.

    My table has four columns: PersonID (int), FirstName (varchar(50)), LastName (varchar(50)), FilmID(int)

    If I try to return only the LastName column I do get a result consisting of all the LastName strings.

    I just can't convert the whole result to a List<Person>.

    What am i doing wrong?

    Stian



    Tuesday, October 14, 2008 2:16 PM
  • Well, I rebuilt the database and now it works. Don't know what was wrong with the old one, but it now converts the query result to a List no problem.

    Stian
    • Marked as answer by Harry Zhu Thursday, October 16, 2008 6:17 AM
    Wednesday, October 15, 2008 6:36 AM
  • Hi,
    I'm getting same kind of problem and unable to fix it. Please help me to fixed. and If rebuilding the DB will fix the problem then let me know the steps to rebuild the Database. My problem description is :

    I'm using WCF service and LINQ for our Silverlight 2 application.

    In my application I'm fetching records from the SQL database using the stored procedure. Below is the interface of my procedure

    List<Usp_GetReportDataResult> GetReportData(int JobId, DateTime StartDate, DateTime EndDate)

    For some JobId I’m able to get the data successfully, but for most of the JobIds I’m getting 'Specified cast is not valid' error exception. JobId is a unique key field of title table.

    Below is the Web Method to get the result using LINQ statement:

    public List<Usp_GetReportDataResult> GetReportData(int JobId, DateTime StartDate, DateTime EndDate)

    {

    // Call to get record from the Database

    WMDBDataContext db = new WMDBDataContext();

    var matchingRecords = from Report in db.Usp_GetReportData(JobId, StartDate, EndDate)

    select Report;

    return matchingRecords.ToList(); //Error is coming in this line.

    }

    Below are the fields and datatypes generated by the LINQ Designer class for Usp_GetReportData.

    private string _Status;

    private string _Protocol;

    private string _Country;

    private string _CountryID;

    private string _LanguageName;

    private string _Subtitles;

    private System.Nullable<short> _VideoID;

    private System.Nullable<System.DateTime> _LastSeenDateET;

    private System.Nullable<int> _DownloadCounts;

    private char _AdjustedInd;

    private System.Nullable<long> _FileSize;

    private System.Nullable<byte> _HourNumber;

    private string _IPAddress;

    ==========================================

    Thanks,

    Mahesh
    Tuesday, February 03, 2009 6:56 AM
  • B"H

     

    Can you tell me what you meant by "Rebuilt the Database"?

    I am having the same issue. and I can not find any help on it.

    Wednesday, April 07, 2010 3:57 PM