3

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

1
  • Show implementation of UserId property Commented Jan 13, 2009 at 13:19

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

1

It could be that the call is crashing in the constructor because the UserId (this.UserId) hasn't been initialised yet.

Comments

Your Answer

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