EF - 和存储库模式 - 多个上下文
我在 ASP.MVC2 中的 EF 上下文中遇到了一些麻烦。
我认为这是改进我创建的存储库数据库上的某些操作的最佳方法。我的存储库类添加、删除、选择许多项目,因此我不需要编写
(using <name>Context = new (... etc ...) ) { ... }
存储库,消除了每个操作的初始化上下文,但不处理上下文。
管理上下文的最佳方法是什么?如果我创建其他存储库类并尝试执行任何需要来自两个上下文的对象的操作,则会出现问题。
有没有其他方法或更好的方法来实现存储库、管理上下文?有什么有趣的图案吗?
I've faced some troubles with context in EF in ASP.MVC2.
I thought that best way to improve some operation on DataBase i've created Repository. My repo class adds, deletes, select many items so i don't need to write
(using <name>Context = new (... etc ...) ) { ... }
Repository eliminates initializing context for every operation, but don't dispose the context.
What is the best way to manage contexts? If i create other repository class and try to do any operation which will need objects from both contexts there is a problem.
Is there any other way or better way to implement repository, to manage contexts? Any interesting pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
上下文是一个工作单元,因此每个 Web 请求都需要一个上下文。
因此,您应该使用构造函数注入(即构造函数参数)为所有存储库提供单个上下文,并在请求结束时将其释放。
大多数 DI 框架会自动执行此操作。
A context is a unit of work, so you want one per web request.
Therefore, you should use constructor injection (i.e., a constructor argument) to supply a single context for all repositories, and dispose it at the end of the request.
Most DI frameworks will do this automatically.
这是一篇关于 EF 之上的存储库模式的好文章:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework。 aspx
您还可以查看有关工作单元模式实现的帖子:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/05/using-unit -of-work-pattern-with-entity-framework.aspx
http://devtalk.dk/2009/06/09/Entity+Framework+40+Beta+1+POCO+ObjectSet+Repository+And+UnitOfWork。 ASPX
Here is a nice post regarding the repository pattern on top of EF:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx
You might also check out posts regarding the Unit of Work pattern implementation:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/05/using-unit-of-work-pattern-with-entity-framework.aspx
http://devtalk.dk/2009/06/09/Entity+Framework+40+Beta+1+POCO+ObjectSet+Repository+And+UnitOfWork.aspx
另请查看这些博客文章:
http:// /initializecomponent.blogspot.com/2010/09/repository-like-facade-for-mocking.html
http://initializecomponent.blogspot.com/2010/09 /repository-like-facade-for-mocking_12.html
Take a look at these blog posts as well:
http://initializecomponent.blogspot.com/2010/09/repository-like-facade-for-mocking.html
http://initializecomponent.blogspot.com/2010/09/repository-like-facade-for-mocking_12.html