Khawar Yunus
Khawar Yunus

Reputation: 141

LINQ to Entities, "An object with the same key already exists in the ObjectStateManager..."

I have a table that has a primary key as a combination of 3 columns 1. AcctNum (string) 2. SrvID (int) 3. RevNum (int)

What I am doing in my code is

  1. I get the row for a specific AcctNum with max RevNum and then I modify some columns (other than the key) for that row.
  2. Then I create a new row ( a new object of the Entity/table type)
  3. I use AutoMapper to map all the values of the row from step 1 above, into the new row I created in step 2 above. Then I modify the RevNum to increase it by one, to create a unique primary key for this new row.

When I do context.TableName.AddObject(newRow) it throws an exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

Even though in the new row I am changing the RevNum to have a unique key. Can someone please tell me what I am doing wrong here?

Upvotes: 1

Views: 456

Answers (1)

Khawar Yunus
Khawar Yunus

Reputation: 141

I resolved this issue myself. The problem is about using AutoMapper to map from an existing entity instance (mapped table row) to a new entity instance (new table row being created).

I stopped using AutoMapper and mapped each property manually one by one and it worked just fine!

Another post with a similar issue: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

Upvotes: 1

Related Questions