实体框架 4 ObjectContext 指南
我在上一篇文章中读到如何通过将 Db 的 ObjectContext 放置在 HttpContext.Current.Items["Db"]; 内的属性中来解决解决方案。这很棒,但我有一个问题。这是否意味着每次我使用存储库时都必须在 HttpContext.Current.Items 中传递 ObjectContext,还是仅在创建或更新引用另一个实体的实体时才需要执行此操作。
在我的存储库类中,我有两种实例化它们的方法,一种是使用 ObjectContext,一种是不使用在实体中创建 ObjectContext 的方法。
I read in a previous article about how to resolve a solution by placing the ObjectContext of my Db in a property within HttpContext.Current.Items["Db"]; This works fantastic, however I have a question. Does this means that every time I use my repository I have to pass the ObjectContext within HttpContext.Current.Items or do I only need to do this when I am creating or updating an entity that has a reference to another entity.
Within my repository classes I have 2 ways of instantiating them, with a ObjectContext and without one in which the ObjectContext is created there within the entity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在单个 HTTP 请求处理中使用的所有存储库之间共享一个上下文。您还应该在请求处理结束时处理上下文。一般来说,您的存储库不应依赖于 HttpContext。最好的方法是在存储库之外创建 ObjectContext 并始终将其传递给其构造函数。您还可以使用一些 IoC 容器(如 Windsor、StructureMap、Ninject 或 Unity)来实现这一点。
You should share one context among all your repositories used in single HTTP request processing. You should also dispose context at the end of request processing. Generally your repository should not be dependent on HttpContext. The best way is to create ObjectContext outside of your repositories and always pass it to their constructor. You can also do that by using some IoC container like Windsor, StructureMap, Ninject or Unity.