简体   繁体   中英

Why do most ASP.NET MVC examples access the database directly in the presentation layer?

Most of (nearly all?) the examples I find on how to set up an ASP.NET MVC project are accessing the database context directly in the controller.

Like this for example:

public class MoviesController : Controller
{
    private MovieDBContext db = new MovieDBContext();

    //
    // GET: /Movies/

    public ViewResult Index()
    {
        return View(db.Movies.ToList());
    }

I also know that there are a lot of controls (at least for the aspx view engine) that you can bind to a table in the database directly as a data source, so that it automatically displays the data.

To me this feels weird and I would like some kind of separation between the presentation layer and the database. Some kind of business layer and/or data layer that maps data from the database to view models, before using them in the view. Is it just me or are the examples all like this because it's easier to do? Is there some great gain that I'm missing? I guess it's a bit faster, but it just feels like I shouldn't use the same models in my database as in my views. I finally found an example that feels more right, where the database models are separated from the view models. But it's one example of a hundred.

What are your thoughts on this?

I understand your concerns as I have the same. It's really a pity that most of the examples out there are not using view models. Because of this people are struggling a lot when they start implementing a real application that differs from the most trivial examples seen in those articles.

As far as directly accessing the database from the controller, I don't think that this is such a big concern. You really don't need to implement lots of layers of abstraction if you don't need them and if they don't bring any additional value to your application. Jimmy Bogard wrote an excellent blog post on the subject of limiting your abstractions.

Most MVC tutorials teach you how to do it simply because it can be done, and that the explanation of the Controller usually comes before explaining the Model.

Take the Movie App tutorial for example - http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3

The majority of these tutorials first teach you how to display data using on the view, then using the controller to display in the view, then entering the data into the model and directing to the view via. the controller.

这是为了使示例简单易行,并专注于手头的主题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM