ASP.Net MVC Controller Constructor shows error System.Web.Mvc.Controller.Session.get returned null

Viewed 229

Basically I want to filter customers of current business from many businesses and I want to done it on one place (constructor). So that I can easily query on db.Customers in rest of the controller. But when I use (Employee)Session["CurrentUser"]; it show error

System.Web.Mvc.Controller.Session.get returned null.

public class SOSRController : Controller
    {
        private BusinessContext db = new BusinessContext();
        public SOSRController()
        {
            Employee employee= (Employee)Session["CurrentUser"];
            db.Customers = (DbSet<Customer>) db.Customers.AsQueryable().Where(x => x.Business.Id == employee.bizId);
        }
        public ActionResult Index()
        {
            List<Customer> LstCust= db.Customers.Where(x => x.Name.Contains("asd")).ToList();
        }
}

Or what could be any other solution of filtering db.Customers at one place only?

1 Answers

It worked. I override Initialize method and now I can get session value. Constructor is concept of classes and Initialize is concept of MVC.

protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

             Employee employee= (Employee)Session["CurrentUser"];
            db.Customers = (DbSet<Customer>) db.Customers.AsQueryable().Where(x => x.Business.Id == employee.bizId);

        }
Related