title: 'Specified cast is not valid' error in ASP.net MVC application. Works locally, and for a time after publishing, but then throws the error
body: <p>My MVC application has worked fine for over a year, but it has now started causing the error below when run online. It works fine locally in debug though.</p>
  
  <p>I made some changes on a Thursday, and it suddenly started causing the error the following Monday (changes were minor, HTML table layout changes). The error is intermittent, and seems to go away for a while (a day or so) if we restart the server. Any ideas what it could be?</p>
  
  <p>Please let me know if you need any more information.</p>
  
  <p>Thanks</p>
  
  <p>Chris</p>
  
  <pre><code>Server Error in '/ISIS' Application.
  --------------------------------------------------------------------------------
  
  Specified cast is not valid. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
  
  Exception Details: System.InvalidCastException: Specified cast is not valid.
  
  Source Error: 
  
  An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  
  
  Stack Trace: 
  
  
  [InvalidCastException: Specified cast is not valid.]
     System.Data.SqlClient.SqlBuffer.get_Int32() +4838981
     System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +38
     Read_Target(ObjectMaterializer`1 ) +275
     System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +29
     System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7667556
     System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
     ISIS2.Controllers.HomeController.Index() in C:\VS2008\VisualStudio\Projects\ISIS2\ISIS2\Controllers\HomeController.cs:66
     lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
     System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
     System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
     System.Web.Mvc.&lt;&gt;c__DisplayClassa.&lt;InvokeActionMethodWithFilters&gt;b__7() +53
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
     System.Web.Mvc.&lt;&gt;c__DisplayClassc.&lt;InvokeActionMethodWithFilters&gt;b__9() +20
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
     System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +395
     System.Web.Mvc.Controller.ExecuteCore() +123
     System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
     System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
     System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +145
     System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
     System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +75
  </code></pre>
  
  <p><em>EDIT</em> here is the code for the index in HomeController:</p>
  
  <pre><code> public ActionResult Index()
          {
              try
              {
              var user = (Staff)Session["CurrentUser"];
  
                  int reminder = 14;
                  if (Request.Form["AlertPeriod"] != null)
                  {
                      reminder = int.Parse(Request.Form["AlertPeriod"]);
                  }
                  if (Request.Form["AlertPeriodLower"] != null)
                  {
                      reminder -= 14;
                  }
                  else if (Request.Form["AlertPeriodHigher"] != null)
                  {
                      reminder += 14;
                  }
                  ViewData["AlertPeriod"] = reminder;
                  ViewData["Alerts"] = (from a in db.Alerts
                                        where a.AlertType.Text == "StaffNews" &amp;&amp;
                                        ((a.StartDate &gt;= DateTime.Today &amp;&amp; a.StartDate &lt;= DateTime.Today.AddDays(reminder)) ||
                                         (a.EndDate &gt;= DateTime.Today &amp;&amp; a.EndDate &lt;= DateTime.Today.AddDays(reminder)) ||
                                         (a.StartDate &lt;= DateTime.Today &amp;&amp; a.EndDate &gt;= DateTime.Today.AddDays(reminder)))
                                        orderby a.EndDate
                                        select a).ToList();
                  ViewData["Targets"] = (from t in db.Targets
                                         where t.StaffID == user.StaffID &amp;&amp;
                                         ((t.TargetContextType.Description == "StudentSet" &amp;&amp; !t.Read) || (t.TargetDiscussions.Any(td =&gt; td.AuthorIsStudent &amp;&amp; !td.Read)))
                                         orderby (t.Enrolment != null ? t.Enrolment.Course.Name : ""), t.DateDue
                                         select t).ToList();
  
                  ViewData["Trips"] = (from t in db.Trips
                                       where t.TripStartDate &gt;= DateTime.Today &amp;&amp; t.TripStartDate &lt;= DateTime.Today.AddDays(14) &amp;&amp; t.StaffID == user.StaffID
                                       orderby t.TripStartDate
                                       select t);
  
                  ViewData["Attending"] = (from a in db.TripAttendings
                                           where a.Trip.StaffID == user.StaffID
                                           select a);
  
  
  
  
  
                  return View("Index", user);
              }
              catch (NullReferenceException e)
              {
                  return RedirectToAction("NonUserIndex");
              }
          }
  </code></pre>