Question

Out of the box, when you create a controller in MVC using Entity Framework, you'll get the basic Get statements that pull data into your controller to display into your view. For example:

    public ActionResult Index()
    {
        var capsules = db.capsules.ToList();
        return View(capsules);
    }

The way I understand it, the best way to write MVC code is to put your data specific logic inside of a Models project. The controller then calls that method in whatever model class you have your logic in, retrieves the data, then sends it to the view. The above example just simply retrieves a list of capsules- very basic. I didn't create a special "CapsuleModelContext" class to handle the capsule retrieval operation because it's being handled in my edmx file.

I guess this all boils down to the question of whether or not I should have the dbContext instantiated in the Controller, or the Model's context class. Out of the box, the dbContext is instantiated inside the Controller. Any advice to best practices here?

Was it helpful?

Solution

Please draw a distinction between your domain models and your view models. Your view models are not responsible for persisting data. Your view models exist simply as containers for entities that are passed to and from your views. Quite simply, they are a model of the view - not the persisted data that the view is designed to manipulate.

With this in mind, then, you should use your controller to interact with whatever entity you are using to manipulate your persisted data (be it a repository or - more directly - a database context). The view model is used as a medium through which to communicate this data from your view to your controller, which, in turn maps your fields to whichever business entities it pertains and interacts with your chosen method of persistence. The view model and your business entity models should be ignorant of each other.

The only logic your view model should contain (and this should, ideally, be kept to a minimum) is logic that is clearly only specific to that view model itself.

I posted another answer to a similar question, which demonstrates a skeleton of how this works in practice:

TextBoxFor() not generating validation markup

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top