title: toList() System.InvalidCastException was unhandled by user code
body: <p>I have written a WCF service using LINQ to SQL (using the following <a href="http://www.codeproject.com/Articles/24561/Integrating-LINQ-to-SQL-queries-within-a-WCF-Servi" rel="nofollow">article at codeporject</a>). I am facing the invalid cast exception when i invoke the .ToList() method of an object after i have already made a wcf function call of the same service against the same database. </p>
  
  <p>The exception is:</p>
  
  <pre><code>System.InvalidCastException was unhandled by user code
    Message=Specified cast is not valid.
    Source=System.Data
    StackTrace:
         at System.Data.SqlClient.SqlBuffer.get_Int64()
         at System.Data.SqlClient.SqlDataReader.GetInt64(Int32 i)
         at Read_Command(ObjectMaterializer`1 )
         at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
         at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
         at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
         at SystemsManager.ACS.GetCommands(Int64 agentId) in E:\Projects\SystemsManager\AgentControlService\ACS.svc.cs:line 167
         at SyncInvokeGetCommands(Object , Object[] , Object[] )
         at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
         at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
    InnerException: 
  </code></pre>
  
  <p>The specific line i am having issue is with the ToList() method</p>
  
  <pre><code> public List&lt;Command&gt; GetCommands(long agentId)
          {
              var cmd = from command in db.Command where (command.AgentId == agentId) select command;
              return cmd.ToList();
          }
  </code></pre>
  
  <p>When debugging, the return statment throws exception. When view the value of cmd.ToList() in Quick Watch of VS 2010, the exception is shown. </p>
  
  <p>Now the strangest thing is: Pressing "Re-Evaluate" button a couple of times changes the exception to required object list in Quick watch. Infact i have to press "Re-evaluate" at least three times.</p>
  
  <p>I have generated client using svcutil tool after my most recent changes to the service/database.</p>
  
  <p>I am calling the method using the following code from a windows service:</p>
  
  <pre><code>var agent = client.GetAgentByIpAddress(myIPAddress);
                  client.Close();
                  if (agent != null)
                  {
                      if (agent.AgentId != -1)
                      {
                          client = new ACSClient();
                          var command = client.GetCommands(agent.AgentId);
                          .....
  </code></pre>
  
  <p>Here is the model of Command in the interface of the wcf service.</p>
  
  <pre><code>[DataContract]
      [Table(Name = "Command")]
      public class Command
      {
          [DataMember, Column(IsPrimaryKey = true, Name = "Command_Id", AutoSync = AutoSync.OnInsert, IsDbGenerated = true, DbType = "Bigint NOT null identity")]
          public long CommandId { get; set; }
  
          [DataMember, Column(Name = "Agent_Id")]
          public long AgentId { get; set; }
  
          [DataMember, Column(Name = "Name")]
          public string CommandName { get; set; }
  
          [DataMember, Column(Name = "Paramters")]
          public string CommandParamters { get; set; }
  
          [DataMember, Column(Name = "Is_Fetched")]
          public bool IsFectched { get; set; }
  
          [DataMember, Column(Name = "Status")]
          public long Status { get; set; }
  
          [DataMember, Column(Name = "Response")]
          public string Response { get; set; }
  
          [DataMember, Column(Name = "Created")]
          public DateTime Created { get; set; }
  
          [DataMember, Column(Name = "Last_Modified")]
          public DateTime LastModified { get; set; }
  
          [DataMember, Column(Name = "Is_Enabled")]
          public bool IsEnabled { get; set; }
      }
  </code></pre>
  
  <p>Important thing is: My database file is located in AppData folder of the WCF service.  I am using only one instance of <strong>db</strong> object (refer to 1st code block above) throughout my wcf service and i am wondering if this could be cause of the problem???</p>
  
  <p>Also, i have called a couple of similar method of this very same wcf service from a desktop application but i have not faced any such issue.</p>
  
  <p>Please help. if more details are needed, please state so.. The only thing that can come to mind is that perhaps the database is in use and when another connection is made to the database by the service, it fails. and retrying it a couple of times using the Quick Watch > Re-evaluate button displays the required values in the watch window without throwing any error. </p>
  
  <p>Kindly help on this one. Quick responses are highly appreciated.</p>
  
  <p>Thanks.</p>
  
  <p>Steve</p>