Goran
Goran

Reputation: 6518

Reference entity from different Context

Lets take a Product as an example. A Product can belong to a particular Group, so it has a reference property of type Group. Currently as it is coded each repository has its own context, so ProductViewModel receives in constructor IProductRepository and IGroupRepository, which have different ObjectContexts.

Question: if I assign Group entity to a particular Product, will Context from ProductRepository treat this assigned Group entity as new entity, since it didn't have any prior knowledge about it, and will try to add it to the database? If yes, how to handle this scenario?

Upvotes: 0

Views: 59

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

If I assign Group entity to a particular Product, will Context from ProductRepository treat this assigned Group entity as new entity, since it didn't have any prior knowledge about it, and will try to add it to the database?

Yes if you are using POCOs without lazy loading and dynamic change tracking (= non proxied entities). If you are using EntityObject based entities or proxied POCOs you will get exception.

If yes, how to handle this scenario?

By using one context shared between both repositories.

Upvotes: 1

Related Questions