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

Sep 24 at 11:59 PM
I use this helpful project in a web app and while calling a service I got the error An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

Code:
            newOpportunities = entities.Where(o => !excludedOpportunties.Contains(o.Id)).ToList();
            existingUserOpportunities.Clear();
            entities.Clear();
            excludedOpportunties.Clear();
            if (newOpportunities.Count > 0)
            {
                _repository.GetRepository<Entities.Opportunity>().InsertRange(newOpportunities);
            }
            foreach (var opportunity in entitiesUpdated)
            {
                _repository.GetRepository<Entities.Opportunity>().Update(opportunity);
            }
            var result = _unitOfWorkAsync.SaveChanges();