简体   繁体   English

数据库访问和ASP.NET MVC

[英]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. 我试图了解asp.net mvc中的数据库访问模型如何工作,一些示例在控制器中起作用,而其他示例在模型中具有示例。

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? 我想知道如何使用ado.net做到这一点,最佳做法是在模型层中使用一个类,然后在那尝试数据库访问?

all examples are with EF and LINQ, I want to know the best way to do it using ado.net. 所有示例都使用EF和LINQ,我想知道使用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 . 视图和控制器位于MVC网站中
  2. The Models are in a separate project. 这些模型在单独的项目中。
  3. The data access code is in a third project called DataAccess or Repository. 数据访问代码位于第三个项目DataAccess或Repository中。

The website has references to the Models and DataAccess projects. 该网站引用了Models和DataAccess项目。 The DataAccess project also has a reference to the Models project. DataAccess项目还具有对Models项目的引用。

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. 您甚至可以将其换成完全不同的数据访问层-例如,从Linq切换到SQL,再切换到Entity Framework或经典的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. 此外,Models项目可用于其他解决方案中,就像松散耦合的数据访问层一样。

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). 我不确定您具体看到过哪些EF示例,但是在许多EF实体中本身就是模型(通常这是一种快速入门的网站入门方法,但不适用于大型网站)。 Basically, the controller is responsible for fetching/generating the model, which it then passes to the view. 基本上,控制器负责获取/生成模型,然后将其传递给视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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