简体   繁体   中英

ASP.NET MVC Database Access Layer

Since I am new to MVC I have a few questions about the database connection.

I am trying to build an MVC application, and so far I have built 2 layers: Model (where my classes are, without any functionality) and Business (there is the functionality for my classes, every class has its own Business class) and there is also my MVC application. Both these layers are separated from the MVC project, I use them as ".dll-s". I am also using the repository pattern and the dependency injection is done by Unity.

Now comes the tricky part (or at least it is for me). I want to bind my application to a database. Most of the tutorials I have found rely on Entity Framework, but I don't want to use it, I want to use ADO.NET (Entity Framework makes me feel like I am giving my "power" away, so I want to manage the SQL on my own). So what is the best way to do it? How can I access the Web.Config from outside and read the connection string (or should I take care of the connection string inside the data access layer)? Is there any best practice how to manage the connection from "outside"? I mean I could easily just create a dbaccess object inside my MVC application, but I don't want that. In the MVC application I just want to use my business(object) classes.

And one more thing. What is the best practice for DataAccess: to build a new layer, or is it also fine to include the functionality inside my business layer? I am more tending to build a third layer, so I can reuse this code for any other application but maybe there are some other approaches.

You can create another project called "DAL" to handle your data access layer which is built using pure ADO.NET. You will add a reference to the entity project so that you can return these entities from your Data access methods. Now from your Business Layer, Add reference to the Data Access projects so that you can access these data access methods from the Business layer classes. From your MVC project, Add reference to your Business project ( and entities project if you are using those entity objects in your MVC project). In this way your MVC project do not have any idea what data access technology you are using.

You do not need to have connection string in your DAL project, Keep that in your UI MVC project and your DAL project will be able to read it as long as you have the proper references added between these projects.

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