开发者

EF - and repository pattern - multiple contexts

开发者 https://www.devze.com 2023-01-05 20:00 出处:网络
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 d

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 o开发者_StackOverflowr better way to implement repository, to manage contexts? Any interesting pattern?


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消