简体   繁体   中英

Layered Architecture using Entity framework where to create the context

I have n tier architecture I have Data Access, Business Service and UI layer. I am using EF 4.0 and MVC. Now question is where to create the context in 1. Business Service and pass the context to Dataacess and return a IQuerable to Data Acess layer. 2. Directly using context in Data Access layer and use Business service just as a proxy( that is basically passing information from DataAcecss and UI).

What is the best place to create 'context'. All the examples available online showing creating context in Data Access Layer.

Thanks for your help!

Agree with @Robert Harvey and @djacobson.

DAL should handle the context, with one exception:

If you're using the Unit of Work pattern.

The UoW is a wrapper for the context, so when you "Create a new UoW", you are actually creating a new data context. As a Unit of Work handles many repositories, it cannot be instantiated in the DAL itself.

UoW (in the context of MVC) would get passed to the Controllers, which gets passed to the Repository, which is then queried upon.

In this case, you would new up the UoW (and hence the context) during application events (global.asax) begin request, and dispose of at end of request (preferably using a DI container).

As @Robert Harvey states, the examples have the right idea. The EF Context is specific to your persistence mechanism (SQL Server database, for example), and therefore belongs in the Data Access layer.

The point of such layering is to make your persistence mechanism invisible to the layers above it, such that you could, for example, change database providers without altering your business / UI code.

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