实体框架上下文?
我真的很难弄清楚 EF Context 在 MVC 应用程序中的管理位置。
我正在使用 Service/Repository/EF 方法,并使用 UnitOfWork 模式及其内部上下文,然后在控制器操作中使用它来利用各种服务。它可以工作,但是通过这样做,我使控制器依赖于 EF,对吗?
有什么建议吗?
I am really having a hard time trying to figure out where the EF Context is managed in an MVC app.
I am using the Service/Repository/EF approach and was playing with the UnitOfWork pattern with a context inside of it, and then using it inside the controller actions to utilize various services. It works, but by doing this, I am making the controllers dependent on EF right?
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您依赖抽象并创建封装 EF 上下文的 IUnitOfWork 和 IRepository,则控制器将依赖于抽象而不是任何具体实现。
存储库和工作单元本身是唯一依赖于实体框架或您正在使用的任何 ORM 的类。
根据请求进行编辑:
一个简单的工作单元实现可以是:
您当然可以通过向服务/存储库注入相同的上下文来确保它们使用与工作单元相同的上下文。
If you rely upon abstractions and create an IUnitOfWork and IRepository encapsulating the EF Context the Controller would be dependent on the abstractions and not any concrete implementation.
The repository and unit of work themselves are the only classes that would be dependent on Entity Framework or whatever ORM you are using.
Edit as per request:
A simple Unit Of Work implementation could be:
You would of course make sure that your services/repositories use the same context as the Unit of Work by injecting the same context into them.
这取决于你的意思是“让控制器依赖于 EF”?
您在控制器中使用任何 EF 相关类吗?如果不是,它们显然不依赖于 EF,您可以轻松地将存储库和工作单元替换为其他实现(例如使用 NHibernate)。
但是,是的,如果您在任何层中使用 EF,则整个 ASP.NET MVC 应用程序都依赖于 EF - 如果不加载 EF DLL,它将无法运行。
That depends on what you meant "making controller dependent on EF"?
Do you use any EF related class in controllers? If not they are obviously not dependent on EF and you can easily swap your repositories and unit of work for other implementation (for example using NHibernate).
But yes whole your asp.net mvc application is dependent on EF if you are using it in any layer - it will simply not run without loading EF dlls.
查看示例代码:http://efmvc.codeplex.com/
Check out the sample code at http://efmvc.codeplex.com/