tags:

views:

1574

answers:

4

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  A: 

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

Kieron
+8  A: 

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

AnthonyWJones
A: 

Thanks very much to you both. I Didn't think about the UserId property!

Mark79
A: 

Hi guys,

I am trying to implement a SportStore project but I am occurring this problem when I want to create an navigation links. See the code below:

public ViewResult Menu() {

        List<NavLink> navLinks = new List<NavLink>();
        navLinks.Add(new CategoryLink(null));


        // add link for every category ;

        var categories = productsRepository.Products.Select(x => x.Category);
        foreach (string category in categories.Distinct().OrderBy(x => x)) ;
        navLinks.Add(new CategoryLink(category));

        return View(navLinks);


    }

Error: An error occurred while creating a controller of type 'WebUI.Controllers.NavController'. If the controller doesn't have a controller factory, ensure that it has a parameterless public constructor.

I will appreciate the help!

Naim