3

I have a similar issue to these posts: I'm posting separately to provide additional information about the issue in my case, along with steps I've taken to debug it.

Basically the site works completely fine for 12+ hours and then suddenly stops working. I'll start getting strange exceptions thrown in LINQ queries that have previously worked fine.

I have included stack traces at the bottom of this post.

Taking the advice found on similar SO posts, I deleted and remade my DBML by dragging the tables directly from the DB in Server Explorer. Comparing the old and the new in Git, I found a few fields that differed:

  • One instance of a varchar(255) being set as an nchar(10) in the dbml
  • Two instances of varchar(255) that previously didn't have NOT NULL in the dbml
  • An int(4) field previously didn't have NOT NULL in the dbml

Some observations/notes:

  • The site works 100% fine for a while and then it just starts throwing these errors
  • I can temporarily fix it by restarting the site in IIS or by restarting MSSQL server, but the problem usually comes back the next day
  • I cannot figure out how to manually replicate it
  • For some pages, I can reload them multiple times and get different but similar exceptions
    • I may get a InvalidOperationException on a line that calls .Count(), then reload it and get a IndexOutOfRangeExcpetion on a line that calls .Any() or .First()
    • Although the exception changes, I always get an exception on certain pages no matter what - they never disappear temporarily
  • I'm using the repository pattern, so each of my classes have a repository class with a private DataContext member - could this be why?
  • The site has a partial view with navigation items which comes from the db, and this always seems to load fine, but loading other things from the db fails. Maybe this block is cached and that's why it continues to work?

The exception always seems to be thrown at this line:

System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539

Any thoughts on why this happening and how to resolve the issue?

EDIT 1: I have added the relevant code above the corresponding stack traces. The exception gets throw when the last line of code executes.

Here are a couple stack traces I was able to copypaste before restarting the site:

IEnumerable<Chapter> toc = (from c in db.Chapters
    where c.Sections.Any()
    orderby c.ChapterNumber ascending
    select c);
return toc.Count();

[InvalidOperationException: Sequence contains more than one element]
   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) +41
   System.Linq.Queryable.Count(IQueryable`1 source) +352
   MvcPaging.PagedList`1.Initialize(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\path\to\my\project\MvcPaging\src\MvcPaging\PagedList.cs:63
   MvcPaging.PagedList`1..ctor(IEnumerable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\path\to\my\project\MvcPaging\src\MvcPaging\PagedList.cs:16
   MvcPaging.PagedList`1..ctor(IEnumerable`1 source, Int32 index, Int32 pageSize) in C:\path\to\my\project\MvcPaging\src\MvcPaging\PagedList.cs:10
   MvcPaging.PagingExtensions.ToPagedList(IEnumerable`1 source, Int32 pageIndex, Int32 pageSize) in C:\path\to\my\project\MvcPaging\src\MvcPaging\PagingExtensions.cs:77
   MyNamespace.Controllers.ChaptersController.TableOfContents(Nullable`1 page) in C:\path\to\my\project\Controllers\ChaptersController.cs:73
   lambda_method(Closure , ControllerBase , Object[] ) +118
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +264
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +129
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +784922
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +314
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976
   System.Web.Mvc.Controller.ExecuteCore() +159
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +37




var contentTop = (new PageRepository()).FindAllPages().Where(p => p.Slug == "login-top");
var contentBot = (new PageRepository()).FindAllPages().Where(p => p.Slug == "login-bottom");
ViewData["ContentAboveTheBox"] = (contentTop.Any() ? contentTop.First().HTML : String.Empty);



[IndexOutOfRangeException: Index was outside the bounds of the array.]
   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.First(IQueryable`1 source) +383
   MyNamespace.Controllers.AccountController.SetLoginContentAreas() in C:\path\to\my\project\Controllers\AccountController.cs:112
   MyNamespace.Controllers.AccountController.LogIn(String userName, String password, Nullable`1 rememberMe, String returnUrl, Nullable`1 IsEnc) in C:\path\to\my\project\Controllers\AccountController.cs:122
   MyNamespace.Controllers.AccountController.LoginPassThru() in C:\path\to\my\project\Controllers\AccountController.cs:82
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +264
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +129
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +784922
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +314
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976
   System.Web.Mvc.Controller.ExecuteCore() +159
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371

There was also an InvalidCastException thrown on one particular page. Updating the dbml did not seem to fix this, but restarting the site did.

1
  • I have posted the LINQ queries above the corresponding stack trace Jul 11, 2011 at 17:41

2 Answers 2

2

Are you disposing your DataContext on each request (you should be)? Or do you have a single DataContext that lives forever (it sounds like this may be the case)?

It sounds like it could be a threading problem.

8
  • I am not currently disposing the DataContexts on each request. I have one as a private member of a class that extends System.Web.Routing.RouteBase and another that extends MembershipProvider - perhaps one of these two is living forever? All my repository models also have this as a private member, but these are always initialized in controller methods. Jul 11, 2011 at 17:24
  • Would it be a good idea to implement IDisposable in my repository classes, keep the DataContext as a private member, and in the repo class's Dispose() method call db.Dispose()? The controller logic would be updated to use using(var pageRepo = new PageRepository()) { ... }. Just wondering if this is the right approach. Jul 11, 2011 at 17:26
  • DataContexts should have a short lifespan. And they are not thread safe. If two threads try to access/alter the objects associated with the DataContext, it may become "corrupt"...forever. You should dispose the DataContext on each request...and instantiate a new one per-request. Some people choose to store it in the HttpContext.Current.Items and bind to the RequestEnd event to dispose of it.
    – Jeff
    Jul 11, 2011 at 17:28
  • Yes, it would be a very good idea, assuming you don't want to share a single DataContext across multiple repositories.
    – Jeff
    Jul 11, 2011 at 17:29
  • The alternative would be using(var dc = new MyDc()) { var repo1 = new Repo1(dc); var repo2 = new Repo2(dc); }
    – Jeff
    Jul 11, 2011 at 17:30
1

Looks like in your LINQ you're making a call to .Single() (or similar) which throws that exception if the IQueryable collection holds more than one element.

Next time, please post your code and not just your stack trace.

3
  • I don't see Single anywhere in the stack trace. And "Index was outside the bounds of the array" is coming from the QueryProvider itself.
    – Jeff
    Jul 11, 2011 at 17:31
  • Jeff is right. I do have a couple calls to .Single() elsewhere, but these are wrapped in try..catch blocks and work fine. The problem I'm having is that it always works until some point in time, and then it stops working. Jul 11, 2011 at 17:35
  • The exception message: "Sequence contains more than one element" (found at the top of your stack) is specifically thrown by .Single() and .SingleOrDefault(), and that was the basis of my answer. Jul 11, 2011 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.