Reputation:
I've created an application controller abstract class that my controllers derive from (As described in the following article)
The following is an example of what my code looks like
public abstract class ApplicationController : Controller
{
private ProjectDataContext datacontext = new ProjectDataContext();
protected ProjectDataContext DataContext
{
get { return datacontext; }
}
public ApplicationController()
{
ViewData["OpenTasks"] = DataContext.Tasks.Where(t => t.UserId == this.UserId).Count();
}
}
This produces the following error which i have determined is due to the "Where" lamda expression:
If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor.
this error is produced whichever way i write the LINQ query and the only way to compile the application is by removing the "Where" clause as follows.
ViewData["OpenTasks"] = DataContext.Tasks.Count();
any ideas what the problem is or how to resolve this as i need to execute the query against the user and not return all entries.
thanks in advance
Upvotes: 3
Views: 4192
Reputation: 189457
Try this instead of using the constructor:-
public abstract class ApplicationController : Controller
{
private ProjectDataContext datacontext = new ProjectDataContext();
protected ProjectDataContext DataContext
{
get { return datacontext; }
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(RequestContext);
ViewData["OpenTasks"] = DataContext.Tasks.Where(t => t.UserId == this.UserId).Count();
}
}
Its quite likely that the current user ID is dependand on the RequestContext
Upvotes: 10
Reputation: 27107
It could be that the call is crashing in the constructor because the UserId (this.UserId) hasn't been initialised yet.
Upvotes: 1