存储库模式和实体框架
我想使用 ASP.NET MVC 2 和实体框架来实现存储库模式,但在此过程中遇到了一些问题。
首先,我有两个实体之间存在关系,例如订单和产品。当我生成 dbml 文件时,它为我提供了一个类 Order ,该类具有映射“ProductSet”的属性,以及一个类 Product ,该类具有映射与 Product 相关的 Order 的属性。
因此,我使用基本的 CRUD 操作创建了像 IReporitory 这样的存储库模式,并在控制器内实现了 ProductRepository 或 OrderRepository。
当我尝试创建 Product 并必须在其上分配我的订单时,就会出现问题,例如 ProductOne.Order = _orderRepository.Find(orderId);
该操作给了我一些奇怪的行为,我找不到找出哪里出了问题。
I want to make an implementation with repository pattern with ASP.NET MVC 2 and Entity Framework but I have had some issues in the process.
First of all, I have 2 entities that has a relationship between them, like Order and Product. When I generate my dbml file it gaves me a class Order with a property that map a "ProductSet" and one class Product with a property that map wich Order that Product relates itself.
So I create my Repository pattern like IReporitory with the basic CRUD operations and inside my controllers I implement the ProductRepository or OrderRepository.
The problem occurs when I try to create Product and have to assign my Order on it, like ProductOne.Order = _orderRepository.Find(orderId);
That operation gave me some strange behavior and I can't find out what is wrong with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题有点缺乏细节,但我的猜测是您在两个存储库中使用两个单独的 ObjectContext,而不是一个。您需要管理 ObjectContext 的生命周期,将其范围限定为单个 Web 请求,并且在该 Web 请求周期的生命周期内只有一个 ObjectContext。
Google 搜索“网络范围的对象上下文”或“对象上下文生命周期”。
例如 http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx
The question is somewhat lacking in details but my guess is that you are using two separate ObjectContexts in your two repositories instead of one. You'll want to manage the lifetime of your ObjectContext to be scoped to a single web request and have only one ObjectContext for the lifetime of that web request cycle.
Google search for 'web scoped objectcontext' or 'objectcontext lifetime'.
e.g. http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx