Linq To SQL Any Throws InvalidOperationException: Sequence contains no elements - asp.net-mvc-3

About once a day or two now my web site starts throwing and error when people try to login and no one can log in until I restart IIS. How can Any() do this and what can I do to fix it?
Here's the function throwing the exception:
public override bool ValidateUser(string username, string password)
{
var db = Access.Context;
var query =
from p in db.Players
where p.PlayerName == username
&& p.Password == password
select p
;
return query.Any();
}
Other LINQ to SQL queries work fine. Here's the stack trace.
InvalidOperationException: Sequence contains no elements
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +1151
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +23
System.Linq.Queryable.Any(IQueryable`1 source) +243
FortyTwoAccess.PlayerProvider.ValidateUser(String username, String password) in C:\dev\FortyTwo\FortyTwoAccess\PlayerProvider.cs:114
FortyTwoClient.Models.AccountMembershipService.ValidateUser(String userName, String password) in C:\dev\FortyTwo\FortyTwoClient\Models\AccountModels.cs:117
FortyTwoClient.Controllers.AccountController.LogOn(LogOnModel model, String returnUrl) in C:\dev\FortyTwo\FortyTwoClient\Controllers\AccountController.cs:42
lambda_method(Closure , ControllerBase , Object[] ) +157
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17

Does works this?
public override bool ValidateUser(string username, string password)
{
var db = Access.Context;
return db.Players.Any(p => p.PlayerName == username && p.Password == password);
}

The fix for this was to not use a class variable to save the context and instead instantiate the context locally in each method wrapped in a using.

Related

Any() method is not working when we connect to MySql

Calling Any() method on a table to check for existence of records throws an exception when we connect to MySql but it is working fine when we connect to SqlServer
I am using the following code:
public IActionResult GetCustomers()
{
DbContext db = new DbContext();
if(db.Customers.Any())//here throws an exception when connect to mysql db
{
//my code
}
return view();
}
My Exception was:
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.'
at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type, MethodInfo method)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Int32 index, TypeMaterializationInfo materializationInfo, Boolean detailedErrorsEnabled, Boolean box)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<>c__DisplayClass13_0.<CreateArrayInitializer>b__0(TypeMaterializationInfo mi, Int32 i)
at System.Linq.Enumerable.<SelectIterator>d__154`2.MoveNext()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey, Boolean detailedErrorsEnabled)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__11_0(CacheKey k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.Create(IReadOnlyList`1 types)
at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.CreateValueBufferFactory(IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.<NotifyReaderCreated>b__14_0(FactoryAndReader s)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
at SampleEfCoreLatest.Controllers.HomeController.GetCustomers() in D:\SampleEfCoreLatest\Controllers\HomeController.cs:line 49
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()

Microsoft Dynamics 2011 N:N LINQ query with where clause containing Guid

I have constructed a simple query to return a Users Team membership (N: N relationship). This works fine for all users, however, when I add a where clause to restrict to a specific user it throws a fault exception (see stack trace below).
Strangely this works fine with "where Users.FullName.StartsWith("Alex")". Does the Dynamics CRM SDK LINQ implementation not support Guides in where clauses?
Any advice?
Example code
using (var service = new OrganizationService("Xrm"))
{
using (var xrm = new XrmServiceContext(service))
{
var AlexUser = xrm.SystemUserSet.Where(p => p.FullName.StartsWith("Alex")).First();
var AlexID = AlexUser.Id;
var Test =
from Users in xrm.SystemUserSet
join TeamMemberships in xrm.TeamMembershipSet on Users.Id equals TeamMemberships.SystemUserId
join Teams in xrm.TeamSet on TeamMemberships.TeamId equals Teams.Id
where Users.Id == AlexID // <-- problematic where clause
orderby Users.FullName
select new
{
FullName = Users.FullName,
UserID = Users.Id,
TeamName = Teams.Name
};
var Test1 = Test.ToList();
}
}
Stacktrace:
Server stack trace: at
System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
operation, ProxyRpc& rpc) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.b__18(IOrganizationService
s) at
Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func2 action) at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups,
String& pagingCookie, Boolean& moreRecords) at
Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression
qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle,
Projection projection, NavigationSource source, List1 linkLookups) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.Query1.GetEnumerator() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
aspirets.crm.test.Program.Main(String[] args) in
C:\Users\a_marshall\documents\visual studio
2010\Projects\aspirets.crm\aspirets.crm.test\Program.cs:line 37 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
Instead of Users.Id, try Users.SystemUserId. Similarly, instead of Teams.Id, try Teams.TeamId.
As for the reason why this works, I'm not aware of any documentation that states this, but because entities in the generated early-binding file inherit from Entity, they necessarily have an Id property. However, because the early-bound OrganizationServiceContext maps entity attributes directly to the CRM database, the tables of which don't contain an Id column, using the Id attribute with the LINQ provider won't work, so you'd have to use the actual database/schema names.

Linq to CRM (early bound) join statement throws exception when lambda expression doesn't

Is there a bug in the Microsoft linq to CRM provider, or am I doing something that linqToCrm doesn't support?
I have a simple function that determines if the user is assigned a role which doesn't work.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
return (from sr in crmService.SystemUserRolesSet
join r in crmService.RoleSet
on sr.RoleId.Value equals r.RoleId.Value
where sr.SystemUserId.Value == systemUserId && r.Name == roleName
select sr.SystemUserId).FirstOrDefault() != null;
}
}
But strangely enough, if I rewrite it as two lambda expressions, it works fine.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
var role = crmService.RoleSet.FirstOrDefault(r => r.Name == roleName);
return role != null
&& crmService.SystemUserRolesSet.FirstOrDefault(
ur => ur.SystemUserId == systemUserId
&& ur.RoleId == role.RoleId) != null;
}
}
The Exception is
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: 'SystemUserRoles' entity doesn't contain attribute with Name = 'name'. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
and the stack trace is
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups, String& pagingCookie, Boolean& moreRecords)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at CRM.Business.IntegrationServices.SystemUserService.IsSystemUserInRole(Guid systemUserId, String roleName, IOrganizationService service)
at CRM.Plugin.OnExecute(IServiceProvider provider)
Where statements from different entities need to be introduced in separate where statements.
The where clause applies a filter to the results, often using a
Boolean expression. The filter specifies which elements to exclude
from the source sequence. Each where clause can only contain
conditions against a single entity type. A composite condition
involving multiple entities is not valid. Instead, each entity should
be filtered in separate where clauses.
The below should probably take care of it.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
return (from sr in crmService.SystemUserRolesSet
join r in crmService.RoleSet
on sr.RoleId.Value equals r.RoleId.Value
where sr.SystemUserId.Value == systemUserId
where r.Name == roleName
select sr.SystemUserId).FirstOrDefault() != null;
}
}

ExecuteReader requires open Connection. Current state: Broken

I'm using StructureMap to inject a LINQ data context (DB class) into my repositories for read queries on a HTTP-context basis, which are queried via a service layer. Everything works fine for a few hours until I get a "Broken" Connection ExecuteReader error (see below for full dump).
Write queries (not read queries) are wrapped in a using (var db = new DB()) {...} statement, which I don't think cause the problem.
I've added MultipleActiveResultSets=true; to my connection string, which seemed to solve the problem for a while, but the error returns until I recycle my application pool, which temporarily solves the problem. Presumably recycling the pool frees all the "broken" data contexes.
StructureMap is configured to inject a data context and repository for each HTTP context:
For<DB>().HttpContextScoped().Use(new DB());
For<IUserRepository>().HttpContextScoped().Use<SqlUserRepository>();
The data context is consumed by my user repository like so:
private DB _db;
public SqlUserRepository(DB db)
{
_db = db;
}
which, in turn conveniently queries the data context like so:
public IQueryable<User> GetUsers()
{
var users = from u in _db.Users
select u; // omitted the rest
}
Which after a few hours ends up with this horrible error:
System.InvalidOperationException: ExecuteReader requires an open and available
Connection. The connection's current state: Broken. at
System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior
runBehavior, Boolean returnStream, String method, DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior
runBehavior, Boolean returnStream, String method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at
System.Data.Common.DbCommand.ExecuteReader() at
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo,
IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[]
subQueries, Object lastResult) at
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos,
IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expressi
on query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression
expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source) at
MyApp.Data.SqlUserRepository.GetUser(String username) at
MyApp.Services.BranchService.GetUser(String username) at
MyApp.Controllers.BranchController.get_CurrentUser() at
MyApp.Controllers.BranchController.OnActionExecuting(ActionExecutingContext filterContext)
at
System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingCon
text filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter,
ActionExecutingContext preContext, Func`1 continuation) at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<>c__DisplayClassf.b__c() at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2
parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
How do I solve this? I really don't want to have to manually wrap every query in a using-statement.
It looks like you're unintentionally are creating a singleton of the Context:
For<DB>().HttpContextScoped().Use(new DB());
In order to create a new context per request, use this instead:
For<DB>().HttpContextScoped().Use(() => new DB());
I would just use a new DataContext for each repository unless you can't for some reason. See this question: Strange behaviour with StructureMap / ASP.MVC / Visual Studio / LinqToSql
Your GetUsers method is returning an IQueryable, meaning the data will not be retrieved from the database until something iterates over it. If you return the IQueryable, close your data reader, and then attempt to iterate over the data, you will get an error, because the connection is closed.
One reason for this would be that your connection could not be opening at all. What ever exception that is coming at the "SqlConnection.Open" statement is being suppressed. If the problem is not in your application it could be that server is unable to grant you a connection. Could be because of a connection leak in your app or in some other database hosted on the same server.

Intermittent "Specified cast is invalid" with StructureMap injected data context

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
Messing around with disposing repositories didn't help, but setting MultipleActiveResultsets to true in my SQL connection string solved the problem.

Resources