简体   繁体   中英

database access and asp.net mvc

I am trying to understand how the database access model works in asp.net mvc, some examples has the work in the controller but other has examples in the model.

I want to know how to do it using ado.net, the best practices is use a class in the model layer and try my database access there?

all examples are with EF and LINQ, I want to know the best way to do it using ado.net.

the database access is in model or controller?

Here is an architectural design to consider:

  1. The Views and Controllers are in the MVC website .
  2. The Models are in a separate project.
  3. The data access code is in a third project called DataAccess or Repository.

The website has references to the Models and DataAccess projects. The DataAccess project also has a reference to the Models project.

This way, the data access code is separate. It is easier to find and maintain. It could be used in another solution. You could even swap it out for a completely different data access layer -- say, switching from Linq to SQL to Entity Framework or classic ADO.Net.

By keeping the Models in a separate project, they can be referenced by both the website and the data access layer. In addition, the Models project could be used in other solutions, just like the loosely-coupled data access layer.

Separating the layers this way makes it easier to add testing , too. That would be made easier if the data access layer/repository utilizes interfaces and dependency injection.

Database access should be done in the controller. I'm not sure specifically what EF examples you've seen, but in many the EF entities themselves are the Model (This is typically a quick and easy way to get started with a website, but isn't viable for big websites). Basically, the controller is responsible for fetching/generating the model, which it then passes to the view.

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