Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3996808
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T07:19:28+00:00 2026-05-20T07:19:28+00:00

I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my

  • 0

I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ.

The error can’t be caused by a mismatched database schema since it works intermittently and it’s on my local dev machine.

Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request?

Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I’m going to do this to all my repositories without copypasting a lot of code.

Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn’t look like it’s happening on my remote deployment box, but I can’t be sure.

I changed all my repositories’ StructureMap life cycles to HttpContextScoped() and the error persists.

Code:

public ActionResult Index()
{
    // error happens here, which queries my page repository
    var page = _branchService.GetPage("welcome"); 
    if (page != null)
    ViewData["Welcome"] = page.Body;
    ...
}

Repository:

GetPage boils down to a filtered query mapping in my page repository.

public IQueryable<Page> GetPages()
{
    var pages = from p in _db.Pages
        let categories = GetPageCategories(p.PageId)
        let revisions = GetRevisions(p.PageId)
        select new Page
        {
            ID = p.PageId,
            UserID = p.UserId,
            Slug = p.Slug,
            Title = p.Title,
            Description = p.Description,
            Body = p.Text,
            Date = p.Date,
            IsPublished = p.IsPublished,
            Categories = new LazyList<Category>(categories),
            Revisions = new LazyList<PageRevision>(revisions)
        };

        return pages;
}

where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries.

Calling code:

public Page GetPage(string slug)
{
    return _pageRepository.GetPages()
                          .WithSlug(slug).FirstOrDefault();
}

WithSlug is just a pipeline filter that adds a where clause to the query.

Error:

Specified cast is not valid.
Exception Details: System.InvalidCastException: Specified cast is not valid.

Stack Trace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539
   System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500
   System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50
   System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383
   Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
   System.Web.Mvc.Controller.ExecuteCore() +162
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T07:19:29+00:00Added an answer on May 20, 2026 at 7:19 am

    Messing around with disposing repositories didn’t help, but setting MultipleActiveResultsets to true in my SQL connection string solved the problem.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We keep getting this error randomly in our web application. System.Data.SqlClient.SqlException: A network-related or
I am seeing this error intermittently. My app throws PageRequestManager is undefined and so
I’m getting an intermittent false negative on the following line of code in an
I'm getting some strange, intermittent, data aborts (< 5% of the time) in some
Intermittently in our app, we encounter LockTimeoutExceptions being throw from SQL CE. We've recently
In the past, and intermittently now, I've used simulation tools like Easy Java Simulations
I have a multithreaded .NET Windows Service that hangs intermittently -- maybe once every
My users are having an intermittent error when using a Windows Forms application built
I'm calling my webservice from a web page and getting a timeout despite setting
We've been having some issues with our MySQL server intermittently. It keeps throwing out

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.