xplat
xplat

Reputation: 8626

Entity Framework 4, SQLCe with POCO problem on delete

I have a SQLCe database which had a unique primary key Id with type uniqueidentifier, and child relationship, 1 to many, where i keep the master id in a column and append unique id for every row too. Now I use POCO entities for my domain model NOT STE. While adding and modifying entities works OK, I have hard time to delete, say for now individual child records, where of course supposed that they have they're own primary key. Soon as i give the deleted list and iterate through each entity while first entity is attached, in the second i get the exception:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I should mention that i first make any add and modify entities to the database while opening a context...disposing and call another method for deletion where of course opens another context and if it ends successfully disposing.

Whats the meaning for this exception that I don't get?

Upvotes: 2

Views: 513

Answers (1)

Tri Q Tran
Tri Q Tran

Reputation: 5690

This exception occurs when you have two different instances of the same entity in your object graph. This exception also occurs in STE but there is a work-around for that.

Basically, you have two entities (POCO), each with a relationship to a third entity. When you try to associate the first entity with the second and try to persist it into the Entity Context, both entities will have a seperate instance of the third and this is where the error is.

Work-around:

Before you make the association between two entities, try to "merge" any related entities together. This is so that the Entity Context does not need to make the decision of which instance of the "common entity" to persist.

Example:

A, (B1,B2), C are entities.

A -- B1

C -- B2

A -- B1 -- C

In this scenario, B1 and B2 are both B entities, just different instances (may be due to different calls to the data store through different contexts). When you want to associate A and C, you must choose to drop B2 and link C to B1.

Upvotes: 0

Related Questions