简体   繁体   English

使用实体框架在哪里创建上下文的分层体系结构

[英]Layered Architecture using Entity framework where to create the context

I have n tier architecture I have Data Access, Business Service and UI layer. 我有n层体系结构,有数据访问,业务服务和UI层。 I am using EF 4.0 and MVC. 我正在使用EF 4.0和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. 现在的问题是在1. Business Service中的哪里创建上下文,并将上下文传递给Dataacess并将IQuerable返回给Data Acess层。 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). 2.在数据访问层中直接使用上下文,并将业务服务用作代理(基本上是从DataAcecss和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. 同意@Robert Harvey和@djacobson。

DAL should handle the context, with one exception: DAL应该处理上下文,但有一个例外:

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. UoW是上下文的包装,因此,当您“创建新的UoW”时,实际上是在创建新的数据上下文。 As a Unit of Work handles many repositories, it cannot be instantiated in the DAL itself. 由于工作单元处理许多存储库,因此无法在DAL本身中实例化它。

UoW (in the context of MVC) would get passed to the Controllers, which gets passed to the Repository, which is then queried upon. UoW(在MVC的上下文中)将传递给控制器​​,控制器将传递给存储库,然后查询存储库。

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). 在这种情况下,您将在应用程序事件(global.asax)开始请求期间更新UoW(并因此更新上下文),并在请求结束时进行处置(最好使用DI容器)。

As @Robert Harvey states, the examples have the right idea. 正如@Robert Harvey所言,这些示例具有正确的想法。 The EF Context is specific to your persistence mechanism (SQL Server database, for example), and therefore belongs in the Data Access layer. EF Context特定于您的持久性机制(例如SQL Server数据库),因此属于数据访问层。

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. 这种分层的目的是使持久性机制对其上方的层不可见,例如,您可以更改数据库提供程序而无需更改您的业务/ UI代码。

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

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