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.