1

I am using EntityFramework code first approach. This is the method to insert and update:

 private void SaveCandidates(Container container, List<Candidate> candidates, bool isInsert)
    {

            var alreadyExists = false;

            foreach (candidate matchingOrderCandidate in candidates)
            {
                alreadyExists = container.Candidates.Any(i => i.Id == candidate.Id);

                if (!alreadyExists && isInsert)
                {
                    container.Entry(candidate).State = EntityState.Added;
                }

                if (alreadyExists && !isInsert)
                {
                    container.Entry(candidate).State = EntityState.Modified;

                }

            }
            container.SaveChanges();
    }

But in case of update, it throws exception

[System.InvalidOperationException] = An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I first Insert Candidates and then some automatic process runs and then this method is called for update and in case of update I get exception at container.SaveChanges(). Any help will be highly appericiated.

Matt Tester
  • 4,663
  • 4
  • 29
  • 32
yo chauhan
  • 12,079
  • 4
  • 39
  • 58

1 Answers1

2

It seems the same issue already solved here An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key try to use instead

container.Entry(candidate).State = EntityState.Modified;

this:

exist = container.Candidates.FirstOrDefault(i => i.Id == candidate.Id);
if(exist != null) container.Entry(exist).CurrentValues.SetValues(candidate);
Community
  • 1
  • 1
Andriy Zakharko
  • 1,623
  • 2
  • 16
  • 37