在 Entity Framework 4 中通过存储库/uow 模式使用多个 ObjectContext
我在 ASP.NET Web 应用程序中使用 EF4 和 StructureMap。我使用存储库/工作单元模式作为 这篇文章中有详细介绍。在代码中,有一行在 global.asax 中委托了 ObjectContext 的设置。
EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());
在网页代码隐藏中,您可以创建一个通用存储库接口,如下所示...
IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();
我的问题是重构此代码的好方法是什么,以便我可以使用多个 ObjectContext 并在代码隐藏中区分它们?基本上我的应用程序中有两个数据库/实体模型,需要在同一页面上查询它们。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
工作单元用于管理跨多个存储库的持久性,而不是跨多个对象上下文。
您将无法使用工作单元在多个上下文中持久保存更改,因为 UoW 只是作为 ObjectContext 的包装器来实现。因此,您需要两个个作品单元。
总的来说,事情会变得混乱。您将有两个新的 OC 并处理每个 HTTP 请求,更不用说事务管理将是一场噩梦。
必须您有两个 ObjectContext 吗?这样做的理由是什么?如果是为了可扩展性,请不要打扰;对于其他事情来说,比如存储库、工作单元和 http 范围管理,这将是非常痛苦的。
如果不了解如何设置存储库,就很难提供好的建议。
尝试为每个对象上下文创建包装类,每个包装类都实现 IUnitOfWork 和一个辅助唯一接口(IEfSqlContext1 等,代表您的模型/上下文之一)。
然后你可以注入你想要的任何上下文。
正如我所说,尽量避免有两个 EDMX/上下文。这比它的价值更麻烦。
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.