Cannot add an entity with a key that is already in use

Rashmi
Rashmi
1068 Points
19 Posts

I'm trying to save data with linq to class. I'm getting following error at line _dbContext.SubmitChanges();:

Cannot add an entity with a key that is already in use
   at System.Data.Linq.ChangeProcessor.TrackUntrackedObjects(MetaType type, Object item, Dictionary`2 visited)
   at System.Data.Linq.ChangeProcessor.TrackUntrackedObjects(MetaType type, Object item, Dictionary`2 visited)
   at System.Data.Linq.ChangeProcessor.TrackUntrackedObjects()
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at WebSolution.....UpdateQuestion(Int64 questionId, String Title,

Following source code:

Question Questions = (from a in _dbContext.Questions where a.QuestionID == questionId select a).SingleOrDefault();
               -----
                Questions.UpdatedDate = DateTime.UtcNow;
                Questions.QuestionPrivacy = QuestionPrivacy;
                Questions.IsActive = 'Y';
                Questions.IPAddress = "";
                foreach (var keyword in keywordArray)
                {
                    var questionKeyword = Questions.QuestionKeywords.FirstOrDefault(x => x.QuestionId == Questions.QuestionID && x.KeywordShortName.ToLower() == keyword.ToLower());
                    if (questionKeyword == null)
                    {
                        questionKeyword = new tbl_QuestionKeyword();
                        questionKeyword.KeywordShortName = keyword;
                        questionKeyword.QuestionId = Questions.QuestionID;
                        Questions.QuestionKeywords.Add(questionKeyword);
                    }
                }
                _dbContext.SubmitChanges();
Views: 13859
Total Answered: 3
Total Marked As Answer: 1
Posted On: 24-Nov-2018 04:17

Share:   fb twitter linkedin
check on db if you have added "Identity Specification" (auto-increment). If not, it may be the reason of failure.
 - beginer  27-Nov-2018 07:37
Answers
andro
andro
118 Points
3 Posts
         

It seams you are trying to add multiple entity through looping. Please check if you are adding duplicate keyword entity.

Posted On: 27-Nov-2018 07:29
sid
sid
10 Points
0 Posts
         

Seems you are missing primary key or an unique key on QuestionKeyword table. Please try to verify the keys in the database. I had same issue since I had missed the PK on the table.

Posted On: 27-Nov-2018 07:41
Rashmi
Rashmi
1068 Points
19 Posts
         

I was getting this error because I had forgotten to set "Identity Specification" (auto-increment) by 1 into the Primary Key field in the database. When I changed this It was good and error had gone.
Thanks Guys...

Posted On: 27-Nov-2018 07:45
mark it as right answer...
 - Rashmi  27-Nov-2018 07:48
great...
 - Stevan  27-Nov-2018 07:50
 Log In to Chat