开发者

Using multiple ObjectContexts in Entity Framework 4 with the repository/uow pattern

开发者 https://www.devze.com 2023-02-05 17:08 出处:网络
i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed开发者_如何转开发 in this post. In the code, there is a line that delegates th

i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed开发者_如何转开发 in this post. In the code, there is a line that delegates the setup of an ObjectContext in global.asax.

EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());

On the web page code-behind, you can create a generic repository interface like so ...

IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();

My question is what is a good approach to refactoring this code so that I can use more than one ObjectContext and differentiate between them in the code-behind? Basically i have two databases/entity models in my application and need to query them both on the same page.


The Unit of Work is used to manage persistence across multiple repositories, not multiple object contexts.

You're not going to be able to persist changes across multiple contexts using a unit of work, as the UoW is simply implemented as a wrapper for a ObjectContext. Therefore, you'll need two unit of works.

Overall, things are going to get messy. You're going to have two OCs newed up and disposed each HTTP request, not to mention transaction management is going to be a nightmare.

Must you have two ObjectContexts? What is the reasoning for this? If it's for scalability, don't bother; it's going to be too painful for other things like your repository, unit of work and http scope management.

It's hard to provide good advice without seeing how you have your repositories set up.

Try creating wrapper classes for each object context, each implementing IUnitOfWork and a secondary unique interface (IEfSqlContext1, etc which represents one of your models/contexts).

Then you can inject whichever context you want.

As I said though, try and avoid having two EDMX/Contexts. It's more trouble than it's worth.

0

精彩评论

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