Somashekhar
Somashekhar

Reputation: 513

An item with the same key has already been added in Entity Framework

I have table with 2 foreign keys. when I am trying to insert duplicate value (for foreign keys) it gives erroe says "An item with the same key has already been added"

below is my code

CheckListTrack CheckListtrack = new CheckListTrack();
trackId = entityCollection.WorkItemTrack.Max(p => p.TrackID) ;
foreach (int ListID in tracklist)
{
    CheckListtrack.WorkItemTrackReference.EntityKey = new EntityKey("SEIESSEntities.WorkItemTrack", "TrackID", trackId);   // foreign key

    CheckListtrack.CheckListReference.EntityKey = new EntityKey("SEIESSEntities.CheckList", "CheckListID", ListID);     // foreign key

    entityCollection.AddToCheckListTrack(CheckListtrack); // error comes after second time control passes here

    }
    curentScope.Complete();
    success = true;

Please help me

Upvotes: 0

Views: 2505

Answers (1)

JanW
JanW

Reputation: 1849

The mistake is that you put the same entity for more times to the entity collection. You have to create the new CheckListTrack() entity within the foreach loop. I guess CheckListTrack has its own primary key auto-increment?

Upvotes: 1

Related Questions