0

How to create controllers in areas accessing the DBContext of the main project in MVC 4?

Hammad Ali Butt
  • 75
  • 4
  • 13

1 Answers1

0

How to create controllers in areas accessing the DBContext of the main project in MVC 4?

The same way you are accessing this DbContext in your main application:

public class SomeAreaController: Controller
{
    public ActionResult Index(int id)
    {
        using (var ctx = new MyDbContext())
        {
            var model = ctx.MyModels.First(x => x.Id == id);
            return View(model);
        }
    }
}

and if your areas are in a separate project then you would move the Data Access Layer containing your models and data contexts to a separate class library that can be reused between your main ASP.NET MVC application and the project containing your areas.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • The problem is that when try to create controller(using VS2010) the DBConext and Model classes of main project are not visible in options.I am using the pluggable architecture for MVC. – Hammad Ali Butt Jun 06 '13 at 07:57
  • What options? Where is this DBContext defined? You need to have reference to the project containing this class. – Darin Dimitrov Jun 06 '13 at 08:00
  • Actually, the problem is that I am trying to built an MVC application using the pluggable modules approach. I have followed the steps mentioned in the tutorial http://geekswithblogs.net/cokobware/archive/2013/01/15/asp.net-mvc-4-pluggable-application-modules.aspx. The tutorial is explaining how to use areas in MVC application. Now,suppose if we have to create controller in Marketing area based on DB context and model classes generated from some database in ProjectDemo.How can it be done?.How to add references in Marketing area. – Hammad Ali Butt Jun 06 '13 at 08:47
  • I already told you - put your data access logic (db contexts and models) in a separate project (class library) that will be referenced in both other projects. This way it will be accessible to both your Areas and main application. – Darin Dimitrov Jun 06 '13 at 08:48
  • Ok.Is there any tutorial available for this.Or is it possible for you to explain. – Hammad Ali Butt Jun 06 '13 at 09:30
  • If you do not understand what a project or an assembly is in .NET you probably should read some basic getting started tutorials in .NET before getting into ASP.NET MVC or you will struggle a lot. – Darin Dimitrov Jun 06 '13 at 09:31