存储库和两个上下文

Repository and two context

我使用的是存储库模式,所以我有一个通用存储库和每个域模型的另外两个存储库。

我有两个控制器; productControllercategoryController。 实际上,我在 categoryController 中创建类别,然后在 productController 中,我将每个类别分配给所需的产品。因此,我必须在 productController.

中使用这两个存储库

我的问题 是我有两个 ObjectContext 对象。当我想用新类别更新我的产品时,出现此错误:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

我该如何解决?

如何增强我的代码以防止出现此问题?

您应该将您的 ObjectContext 注入到您的存储库实例中,这样您就可以将相同的实例注入到两个存储库中并避免错误。

如果您使用 IoC 容器,它应该允许您指定它创建的实例的范围。如果您使用的是 Autofac,则需要使用 InstancePerRequest